php:通过json数组循环
我有一个JSON数组:
[ { "var1": "9", "var2": "16", "var3": "16" }, { "var1": "8", "var2": "15", "var3": "15" } ]
我怎样才能通过使用PHP循环这个数组?
如果需要关联数组,则将第二个函数参数设置为true
如果您需要关联数组,则某些版本的php需要第二个参数为true
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]'; $array = json_decode( $json, true );
使用json_decode()
解码JSONstring,然后使用常规循环遍历它:
$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 }
首先你必须解码你的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; }
使用json_decode
将JSONstring转换为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'