Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: loop through json array

Tags:

json

php

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?

like image 929
superUntitled Avatar asked Jan 19 '11 02:01

superUntitled


People also ask

How to loop through the array of JSON objects in PHP?

Show activity on this post. 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.

How do I loop through an array of objects in PHP?

Use the foreach($array_name as $element) to iterate over elements of an indexed array. Use the foreach($array_name as $key => $value) to iterate over elements of an associative array.

What is JSON array in PHP?

A JSON array is produced by assigning a contiguous integer-indexed PHP array into a JSON domain tree path. A PHP array variable is contiguous integer-indexed if it contains only integer keys that are sequenced from 0 to n -1 (where n is the total number of items in the array).


2 Answers

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 } 
like image 159
chustar Avatar answered Oct 05 '22 12:10

chustar


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 ); 
like image 34
Scuzzy Avatar answered Oct 05 '22 12:10

Scuzzy