JSON结果是一个stdObject但是如何遍历它?

时间:2011-03-11 15:33:44

标签: php arrays json object

我的数据在变量中,当输出看起来像这样

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" } 

问题是如何获得每个元素。我已经尝试将对象转换为数组,但这是必要的吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

为什么这不起作用,即不为变量赋值:

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;
     }
   } 
}