将关联数组值转换为变量,这些变量是来自cookie的字符串格式

时间:2015-01-01 15:09:21

标签: php jquery arrays json associative-array

我从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

这是有效的回报但不是我想要的。这里有任何帮助来单独获取值吗?

1 个答案:

答案 0 :(得分:3)

使用json_decode($getcart, true);json_decode() true中的JSON参数将true转换为数组。如果没有array()参数,则会将其转换为object的{​​{1}}。

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