Page 1 of 1

Please Help Me with JSON and PHP Multi-Dimentional Array

Posted: Wed Jan 05, 2011 4:50 pm
by gunty233
Hi,

I have been banging my head against a brick wall the past few days trying to figure this out after reading so many tutorial and forum post but I still can't figure it out. I would be very grateful if someone could help me out.

Basically I am being supplied with this JSON Data structure:

Code: Select all

$json='{
    "countries": {
        "country": [
            {
                "@attributes": {
                    "Name": "Germany",
                    "Lat": "52.6847077739394",
                    "Lng": "-6.81976318359375",
                    "ZoomLevel": "7"
                }
            },
            {
                "@attributes": {
                    "Name": "Sweeden",
                    "Lat": "54.00131186464818",
                    "Lng": "-7.36358642578125",
                    "ZoomLevel": "8"
                }
            }
        ]
    }
}';
I decode the JSON data structure as a PHP array and I print out the contents of the array for debugging purposes:

Code: Select all

$json_array=json_decode($json,true);

print_r($json_array);

Heres what the outputed array looks like:

Code: Select all

Array ( 
				[countries] => Array ( 
						[country] => Array ( 
								[0] => Array ( 
												[@attributes] => Array ( 
												[Name] => Germany 
												[Lat] => 52.6847077739394 
												[Lng] => -6.81976318359375 
												[ZoomLevel] => 7 	   )
										     )
											 
								[1] => Array (  [@attributes] => Array ( 
												[Name] => Sweeden 
												[Lat] => 54.00131186464818 
												[Lng] => -7.36358642578125 
												[ZoomLevel] => 8 		) 
											 )
									      )
									)
				)
I want to be able to access all the country names contained in [Name]

Can anyone please help me on how to do this correctly as I've tried lots of code with multi-dimensional arrays but I've had no luck. I am not able to acces the variable correctly.

Thanks in advance.

Re: Please Help Me with JSON and PHP Multi-Dimentional Array

Posted: Wed Jan 05, 2011 4:51 pm
by Benjamin

Code: Select all

foreach ($data['countries']['country'] as $row) { echo $row['Name']; }

Re: Please Help Me with JSON and PHP Multi-Dimentional Array

Posted: Wed Jan 05, 2011 5:02 pm
by gunty233
Hi,
Thanks for the quick response.

I've tried your suggestion but unfortunatly its not working, its giving me a PHP error message : " Message: Undefined index: Name"

Any other suggestions ?

UPDATE:

I figured it out using your code

Your solution was just missing [@attributes]

This code works perfect:

Code: Select all

foreach ($json_array['countries']['country'] as $row) { 
			       echo $row['@attributes']['Name']; 
			}