67

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?

Jonah
10.1k5 gold badges49 silver badges80 bronze badges
asked Jan 19, 2011 at 2:34
1
  • Use json_decode to convert it to a PHP array. Commented Jan 19, 2011 at 2:37

4 Answers 4

104

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
}
TSE
3561 silver badge10 bronze badges
answered Jan 19, 2011 at 2:37
1
  • 1
    +1 for this. it is exactly what I was trying to do, however the lack of the true for the associative array was giving me an error. Commented Jan 19, 2011 at 3:06
66

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 );
answered Jan 19, 2011 at 2:39
1
  • 1
    There's no version specific reference to the second assoc argument Commented Jan 19, 2011 at 4:18
46

First you have to decode your json :

$array = json_decode($the_json_code);

Then after the json decoded you have to do the 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.

if($key == 'var1'){
 echo $value;
}
answered Jan 19, 2011 at 12:56
0
12

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

$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);
var_dump($data[0]['var1']); // outputs '9'
answered Jan 19, 2011 at 2:37
1
  • 1
    This doesn't loop through the array tho. It just retrieves the first value? Commented Jul 13, 2016 at 23:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.