php - json遍历 - jquery json each




php:循環遍歷json數組 (3)

我有一個json數組:

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

如何使用php循環遍歷此數組?


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

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

首先你必須解碼你的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