将关联数组值获取到变量中,这是来自 cookies 的字符串格式

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

我正在从字符串格式的 cookie 中获取此关联数组类型的值 -

[{"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"}]" 

如果我通过 -

将其转换为数组
json_encode($getcart);

通过 -

将其带到另一个数组进行进一步操作
$ar=array();
$ar = json_decode($getcart);

我需要帮助 -

正在通过 'id' 获取所有值。对于前。如果我按 id=7 搜索,我需要接收其值 quantity=3 和 price-1500 以及 title-shoes

我在这里尝试过但失败了-

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

哪些有效 returns 但不是我想要的。对单独获取值有帮助吗?

使用json_decode($getcart, true);。这里 true 中的 json_decode() 参数将 JSON 转换为数组。如果没有 true 参数,它将转换为 objectarray()

$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>';