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

Kal*_*oon 2 php json

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

"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
Run Code Online (Sandbox Code Playgroud)

在我用PHP解码之后json_decode(),我不知道输出是什么类型的结构.我以为它会是一个数组,但在我要求count()它之后说它是"0".如何遍历此数据以便获取列表中每个产品的属性.

谢谢!

Jos*_*h M 10

要将json转换为数组使用

 json_decode($json, true);
Run Code Online (Sandbox Code Playgroud)


小智 8

你可以使用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
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)


Bor*_*ora 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
}
Run Code Online (Sandbox Code Playgroud)

得到数数

echo count($array); // 2
Run Code Online (Sandbox Code Playgroud)