varun kumar
varun kumar

Reputation: 115

Get associative array values into variables,which is in string format from cookies

I am getting this associative array-type values from the 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 array by -

json_encode($getcart);

taking this to another array for further operations by -

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

I need help in -

Fetching all the values by its 'id'. For ex. If i search by id=7, i need to receive its values quantity=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 returns but not what i want. Any help here to fetch the values individually?

Upvotes: 3

Views: 236

Answers (1)

MH2K9
MH2K9

Reputation: 12039

Use json_decode($getcart, true);. Here true parameter in json_decode() convert JSON to array. Without true parameter it is converted to array() of 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>';

Upvotes: 3

Related Questions