如何在PHP中循环通过json解码的数据?
我有一个JSON格式的产品列表,需要解码:如何在PHP中循环通过json解码的数据?,php,json,Php,Json,我有一个JSON格式的产品列表,需要解码: "[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]" 在我用PHP用json\u decode()解码它之后,我不知道输出是什么样的结构。我假设它是一个数组,但在我询问count()之后,它会说它是“0”
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
在我用PHP用json\u decode()
解码它之后,我不知道输出是什么样的结构。我假设它是一个数组,但在我询问count()
之后,它会说它是“0”。如何循环使用这些数据,以便获得列表中每个产品的属性
谢谢 尝试以下代码:
$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
}
数一数
要将json转换为数组,请使用
json_decode($json, true);
你看过说明书了吗 或者只是找到一些复制品 使用谷歌
json_decode($json, true);
第二个参数。如果为true,它将返回数组。您可以使用json\u decode()将json转换为数组
e、 g,
然后你可以循环数组变量,比如
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
}
您可以在php fiddle online上试用该代码,对我有用
$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);
$decoded_json=json_decode($list);,然后将数组输出为echo“”;打印($decoded_json);回声“;然后将输出粘贴到这里
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
}
$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);