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.
jrbedard
3,7345 gold badges37 silver badges35 bronze badges
asked Sep 26, 2016 at 11:51
2 Answers 2
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;
}
answered Sep 26, 2016 at 11:55
Comments
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)
answered Sep 26, 2016 at 11:53
4 Comments
Pancho
How is this different from the answer above which should also work with any $key
Lampe2020
@Pancho It tells the reader that you don't need the key in a
foreach
loop and it also works without.Pancho
@Lampe2020 I understand that these answers came out at exactly the same time which is I suppose why it happened and that this one was actually first. However should timing not have been the case I stand by my comment that only one of these answers was needed - the other could just have added a comment to the first.
Lampe2020
@Pancho Probably, yes. You've got that point.
lang-php
print_r($obj)
$i<count($obj['a'])
should be$i<count($obj)
. You want to count the total elements in the array, not the elements in the first value, which is 0 in this case. Alternativelyforeach
is more readable.{"1": "a", ... etc}
.