66

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
  • 9,991
  • 5
  • 45
  • 79
superUntitled
  • 22,351
  • 30
  • 83
  • 110
  • Use [json_decode](http://php.net/manual/en/function.json-decode.php) to convert it to a PHP array. – Phil Jan 19 '11 at 02:37

4 Answers4

99

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
  • 356
  • 1
  • 8
chustar
  • 12,225
  • 24
  • 81
  • 119
  • 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. – superUntitled Jan 19 '11 at 03: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 );
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
45

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;
}
Community
  • 1
  • 1
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'
Community
  • 1
  • 1
lonesomeday
  • 233,373
  • 50
  • 316
  • 318