我有一个json数组:
[
{
"var1": "9",
"var2": "16",
"var3": "16"
},
{
"var1": "8",
"var2": "15",
"var3": "15"
}
]
Run Code Online (Sandbox Code Playgroud)
如何使用php循环遍历此数组?
chu*_*tar 70
解码JSON字符串json_decode()
,然后使用常规循环遍历它:
$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
}
Run Code Online (Sandbox Code Playgroud)
Scu*_*zzy 60
如果需要关联数组,请将第二个函数参数设置为true
如果需要关联数组,某些版本的php需要第二个参数为true
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
Run Code Online (Sandbox Code Playgroud)
小智 33
首先你必须解码你的json:
$array = json_decode($the_json_code);
Run Code Online (Sandbox Code Playgroud)
然后在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 ...
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想要一些特定的东西,只需要这样的钥匙.把它放在最后一个foreach之间.
if($key == 'var1'){
echo $value;
}
Run Code Online (Sandbox Code Playgroud)
lon*_*day 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'
Run Code Online (Sandbox Code Playgroud)