我从字符串格式的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
{
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
这是有效的回报,但不是我想要的.这里有任何帮助来分别获取值吗?
解决方法:
使用json_decode($getcart,true);.此处json_decode()中的true参数将JSON转换为数组.如果没有true参数,则将其转换为object的array().
$getcart = '[{"id":"7","quantity":"3","price":1500,"title":"Shoes"},{"id":"9","quantity":"4","price":1290,"title":"Shirt"}]';
$arr = json_decode($getcart, true);
print '
';
foreach($arr as $val){
print_r($val);
//print $val['id'];
//print $val['quantity'];
//print $val['price'];
//print $val['title'];
}
print '';
标签:associative-array,arrays,json,php,jquery
来源: https://codeday.me/bug/20191120/2047463.html