Get the values โ€‹โ€‹of an associative array into variables that are in string format from cookies.

I am getting these associative array type values โ€‹โ€‹from a cookie, which is in string format -

[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]

var_dump($getcart);  //  return of this is(just to confirm) -

string(111) "[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]" 

      

If I convert this to an array with

json_encode($getcart);

      

taking this into another array for further operations with

$ar=array();
$ar = json_decode($getcart);

      

I need help -

Retrieving all values โ€‹โ€‹by its "id". Ex. If I search for id = 7 I need to get its values โ€‹โ€‹= 3 and price-1500 and title shoes

I have tried and failed here -

for($i=0;$i<sizeof($ar);$i++)
{
    print_r(array_values($ar[1]));  // gives back ----> Array ( [0] => stdClass Object ( [id] => 7 [quantity] => 3 [price] => 1500 [title] => casual blue strip ) [1] => stdClass Object ( [id] => 9 [quantity] => 4 [price] => 1290 [title] => United Colors of Benetton shirt ) ) Array ( [0] => stdClass Object ( [id] => 7 [quantity] => 3 [price] => 1500 [title] => casual blue strip ) [1] => stdClass Object ( [id] => 9 [quantity] => 4 [price] => 1290 [title] => United Colors of Benetton shirt ) ) 
}

echo $ar  // gives ------> ArrayArray

      

which are valid but not what I want. Any help here for getting the values โ€‹โ€‹separately?

+3


source to share


1 answer


Use json_decode($getcart, true);

. Here the parameter true

in json_decode () converts JSON

to an array. Without a parameter, true

it is converted to array()

from object

.



$getcart = '[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]';
$arr = json_decode($getcart, true);

print '<pre>';
foreach($arr as $val){
    print_r($val);
    //print $val['id'];
    //print $val['quantity'];
    //print $val['price'];
    //print $val['title'];
}
print '</pre>';

      

+3


source







All Articles