我有一个json数组:
[
{
"var1": "9",
"var2": "16",
"var3": "16"
},
{
"var1": "8",
"var2": "15",
"var3": "15"
}
]
如何使用php循环遍历此数组?
答案 0 :(得分:64)
使用json_decode()
解码JSON字符串,然后使用常规循环遍历它:
$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');
foreach($arr as $item) { //foreach element in $arr
$uses = $item['var1']; //etc
}
答案 1 :(得分:54)
如果需要关联数组
,请将第二个函数参数设置为true 如果需要关联数组,某些版本的php需要第二个参数为
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
答案 2 :(得分:29)
首先你必须解码你的json:
$array = json_decode($the_json_code);
然后在json解码后你必须做foreach
foreach ($array as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
如果您想要特定的东西,只需要这样的钥匙。把它放在最后一个foreach之间。
if($key == 'var1'){
echo $value;
}
答案 3 :(得分:10)
使用json_decode
将JSON字符串转换为PHP数组,然后在其上使用普通的PHP数组函数。
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);
var_dump($data[0]['var1']); // outputs '9'