如何在PHP中循环这个json解码数据?

时间:2013-08-27 11:44:14

标签: php json

我在JSON中有这个需要解码的产品列表:

"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"

在用json_decode()在PHP中解码之后,我不知道输出是什么类型的结构。我假设它是一个数组,但在我要求count()之后它说“0”。如何循环访问这些数据,以便获得列表中每个产品的属性。

谢谢!

5 个答案:

答案 0 :(得分:9)

要将json转换为数组,请使用

 json_decode($json, true);

答案 1 :(得分:8)

你可以使用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

然后你可以循环数组变量,如

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
}

答案 2 :(得分:7)

请尝试以下代码:

$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

答案 3 :(得分:1)

您查看了手册吗?

  

http://www.php.net/manual/en/function.json-decode.php

或者只是找一些副本?

  

How to convert JSON string to array

使用GOOGLE。

json_decode($json, true);

第二个参数。如果是,则返回数组。

答案 4 :(得分:0)

你可以在网上试试PHP小提琴代码,适合我

 $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);
相关问题