php: loop through json array
I have a json array:
[
{
"var1": "9",
"var2": "16",
"var3": "16"
},
{
"var1": "8",
"var2": "15",
"var3": "15"
}
]
How can I loop through this array using php?
Solution 1:
Decode the JSON string using json_decode()
and then loop through it using a regular loop:
$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
}
Solution 2:
Set the second function parameter to true if you require an associative array
Some versions of php require a 2nd paramter of true if you require an associative array
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );