php:循环通过 json 数组

2022-08-30 09:13:59

我有一个json数组:

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

如何使用php遍历此数组?


答案 1

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

答案 2

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

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

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

推荐