简体   繁体   中英

JSON result is an stdObject but how to traverse it?

I have my data in a variable which when output looks something like this

object(stdClass)#1 (20) { ["Link"]=> object(stdClass)#2 (2) { ["Text"]=> string(30) "A.Ilkley Moor Medical Practice" ["Uri"]=> string(87) "http://v1.syndication.nhschoices.nhs.uk/organisations/gppractices/25599?apikey=LDVVTHBM" } ["Address"]=> object(stdClass)#3 (6) { ["Line1"]=> string(28) "Ilkley Moor Medical Practice" ["Line2"]=> string(17) "The Health Centre" ["Line3"]=> string(12) "Springs Lane" ["Line4"]=> string(6) "Ilkley" ["Line5"]=> string(0) "" ["Postcode"]=> string(7) "LS298TH" } 

Question is how do I get to each individual element. I have tried converting the object to an array but is this necessary?

foreach ($data as $object)
{
  foreach ($object as $property=>$value)
   {
     echo $property." has the value ". $value;
   } 
}

Why would this not work, ie not assign values to the variables :

foreach (json_decode($data) as $object)
{
  foreach ($object as $property=>$value)
   {
     echo $property." has the value ". $value;
     switch ($property) {
        case 'Text':            
            $practice_name = $value;
            break;
        case 'Uri':
            $Website = $value;          
            break;
        case 'Line1':
            $Address1 = $value;
            break;
     }
   } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM