我有一个JSON中需要解码的产品列表:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
当我用json_decode()
在PHP中解码后,我不知道输出是什么样的结构。我以为它是一个数组,但当我要求count()
后,它说它是"0"。如何循环浏览这些数据,以便获得列表中每个产品的属性。
谢谢!
要将json转换为数组,请使用
json_decode($json, true);
您可以使用json_decode()将json转换为数组。
例如
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
然后你可以循环数组变量,比如
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
尝试以下代码:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
获取计数
echo count($array); // 2
您查看手册了吗?
http://www.php.net/manual/en/function.json-decode.php
或者只是找到一些重复的?
如何将JSON字符串转换为数组
使用GOOGLE。
json_decode($json, true);
第二个参数。如果为true,则返回array。
您可以在线尝试php-fiddle上的代码,适用于我的
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);