如何在 PHP 中遍历这个 json 解码数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18464457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through this json decoded data in PHP?
提问by Kaltsoon
I've have this list of products in JSON that needs to be decoded:
我有需要解码的 JSON 产品列表:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode()
, I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count()
it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
在我用 PHP 解码后json_decode()
,我不知道输出是什么类型的结构。我假设它是一个数组,但在我要求count()
它之后说它是“0”。我如何遍历这些数据,以便获得列表中每个产品的属性。
Thanks!
谢谢!
回答by Josh M
To convert json to an array use
要将 json 转换为数组,请使用
json_decode($json, true);
回答by Josh M
You can use json_decode() It will convert your json into array.
您可以使用 json_decode() 它将您的 json 转换为数组。
e.g,
例如,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
然后你可以像这样循环数组变量,
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
}
回答by Bora
Try like following codes:
尝试如下代码:
$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
}
Get Count
获取计数
echo count($array); // 2
回答by M1K1O
Did you check the manual ?
你看说明书了吗?
Or just find some duplicates ?
或者只是找到一些重复项?
Use GOOGLE.
使用谷歌。
json_decode($json, true);
Second parameter. If it is true, it will return array.
第二个参数。如果为真,它将返回数组。
回答by sven
You can try the code at php fiddle online, works for me
您可以在线尝试 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);