Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through JSON object values in PHP?

I have a JSON Object and I want to loop through the values:

$json = '{"1":a,"2":b,"3":c,"4":d,"5":e}';
$obj = json_decode($json, TRUE);
for($i=0; $i<count($obj['a']); $i++) {
    echo $i;
}

I want the $i to display the abcde that are the values in the object.

like image 365
JSking Avatar asked Sep 26 '16 11:09

JSking


People also ask

How to get data from Multidimensional JSON array in PHP?

I assume you've decoded the string you gave with json_decode method, like... $data = json_decode($json_string, TRUE); To access the stats for the particular worker, just use... $worker_stats = $data['workers']['[email protected]'];

Does PHP support JSON?

The PHP FilePHP has some built-in functions to handle JSON.

Why we use JSON in PHP?

JSON is portable because parsers and writers are available for many, many languages. This means that JSON that a PHP script generates can be very easily understood by a JavaScript script. It is the best way to transmit complex structures like arrays and objects, and have it still be compatible with multiple languages.


1 Answers

Try using.

$json = '{"1":"a","2":"b","3":"c","4":"d","5":"e"}';
 $obj = json_decode($json, TRUE);

foreach($obj as $key => $value) 
{
echo 'Your key is: '.$key.' and the value of the key is:'.$value;
}

p.s not tested ;-)

like image 136
Puya Sarmidani Avatar answered Oct 06 '22 19:10

Puya Sarmidani