Skip to content
Advertisement

Looping through JSON Data

There is probably a simple response to this, but I’ve scoured the net trying to find an answer.

Imagine the following JSON data ($json):

{'Top': [{  'Mid1': 'Value1',
            'Mid2': 'Value2',
            'Mid3': [   {'Bottom': 'Value3'},
                        {'Bottom': 'Value4'},
                        {'Bottom': 'Value5'},]
        }]}

What I’d like to do is loop through the data contained within Mid3, so that I can display Bottom1, Bottom2, etc.. so I thought this would work:

foreach($json->Top->Mid3 as $item)
{
echo $item->Bottom;
}

Does anyone know where I’m going wrong?

Advertisement

Answer

Your foreach is looking for Mid3 elements and not there child nodes.

Use:

foreach($json->Top->Mid3->Bottom as $item)
{
   echo $item;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement