php:循环遍历 json 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4731242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:10:35  来源:igfitidea点击:

php: loop through json array

phpjson

提问by superUntitled

I have a json array:

我有一个 json 数组:

[
    {
        "var1": "9",
        "var2": "16",
        "var3": "16"
    },
    {
        "var1": "8",
        "var2": "15",
        "var3": "15"
    }
]

How can I loop through this array using php?

如何使用 php 遍历这个数组?

回答by chustar

Decode the JSON string using json_decode()and then loop through it using a regular loop:

使用解码 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
}

回答by Scuzzy

Set the second function parameter to true if you require an associative array

如果需要关联数组,请将第二个函数参数设置为 true

Some versions of php require a 2nd paramter of true if you require an associative array

如果需要关联数组,某些版本的 php 需要第二个参数为 true

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );

回答by Lucas Costa oliveira

First you have to decode your json :

首先你必须解码你的 json :

$array = json_decode($the_json_code);

Then after the json decoded you have to do the foreach

然后在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 ...
    }
}

If you want something specific just ask for a key like this. Put this between the last foreach.

如果您想要特定的东西,只需要求这样的钥匙即可。把它放在最后一个 foreach 之间。

if($key == 'var1'){
 echo $value;
}

回答by lonesomeday

Use json_decodeto convert the JSON string to a PHP array, then use normal PHP array functions on it.

使用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'