JSking
JSking

Reputation: 419

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.

Upvotes: 12

Views: 47809

Answers (2)

Puya Sarmidani
Puya Sarmidani

Reputation: 1289

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;
}

Upvotes: 32

Daniel Dudas
Daniel Dudas

Reputation: 3002

The shortest way to iterate it and this way you don't care about index is to use foreach like this:

foreach($obj as $value) {
 echo $value;
}

For example you don't have a index 0 in your $obj. From what I see it starts from 1. This way it's working with any index (not just numeric)

Upvotes: 10

Related Questions