【问题标题】:JSON result is an stdObject but how to traverse it?JSON 结果是一个 stdObject 但如何遍历它?
【发布时间】:2011-03-11 15:33:43
【问题描述】:

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

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

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

【问题讨论】:

    标签: php arrays json object


    【解决方案1】:
    foreach ($data as $object)
    {
      foreach ($object as $property=>$value)
       {
         echo $property." has the value ". $value;
       } 
    }
    

    【讨论】:

    • 其实问题是我需要对变量进行json_decode($data)。
    • 尝试将 $value 分配给变量不起作用:
    【解决方案2】:

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

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

    【讨论】:

    • 网站值导致了问题。没有调试器很难发现。
    猜你喜欢
    • 2015-12-17
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    • 2020-07-12
    相关资源
    最近更新 更多