views:

48

answers:

1

for this json api response I am able to parse with json_decode:

 $string = '{"name": "Google",
     "permalink": "google",
     "homepage_url": "http://google.com",
     "blog_url": "http://googleblog.blogspot.com",
     "blog_feed_url": "http://googleblog.blogspot.com/feeds/posts/default?alt=rss",
     "twitter_username": "google",
     "category_code": "search",
     "number_of_employees": 20000,
     "founded_year": 1998,
     "founded_month": 9,
     "founded_day": 7,// bla bla.....}';

$obj=json_decode($string);
echo $obj->number_of_employees."<br>";// 20000
echo $obj->founded_year; //1998

I am getting result with above but getting blank result with below one:

$string =  '{"offices":
  [{"description": "Google Headquarters",
    "address1": "1600 Amphitheatre Parkway",
    "address2": "",
    "zip_code": "",
    "city": "Mountain View",
    "state_code": "CA",
    "country_code": "USA",//blah blah }]//blah blah...}';

$obj=json_decode($string);
echo $obj->address1."<br>";// ""
echo $obj->city; //""

I am aware that address1 is again inside another array or loop but dont know how to retrieve it...any ideas??

+3  A: 

You will need something like:

foreach($obj->offices as $office) {
    echo $office->address1; // The first would be '1600 Amphitheatre Parkway'
}

To view contents of your decoded json do something like the following:

echo "<pre>";
print_r($obj);
echo "</pre>";

In your case this would give you:

stdClass Object
(
    [offices] => Array
        (
            [0] => stdClass Object
                (
                    [description] => Google Headquarters
                    [address1] => 1600 Amphitheatre Parkway
                    [address2] => 
                    [zip_code] => 
                    [city] => Mountain View
                    [state_code] => CA
                    [country_code] => USA
                )

        )

)
Lizard
Great thanks it is working....one more question I havent mention all result here...adress1 carries multipple results say 1600 Amphitheatre Parkway,112 S. Main St.10 10th Street NEPlaza, and more...how do I control this?? I want say only one or two address..
mathew
You maybe use the implode function, $addresses = implode(",", $address1); This will put all addresses into an array separated by comma
Lizard
Oh I am always forgetting these commands...$addresses = explode(",", $address1); echo $addresses[0]; this will give the result...
mathew
I am getting an Invalid implode function error message...why is this??
mathew
check the php manual for those commands
Lizard
it isn't the function problem something else is causes ...
mathew