【问题标题】:Getting JSON data in PHP在 PHP 中获取 JSON 数据
【发布时间】:2010-03-25 05:33:52
【问题描述】:

我有一个这样的 JSON 数据:

{
 "hello":
  {
   "first":"firstvalue",
   "second":"secondvalue"
  },
  "hello2":
  {
   "first2":"firstvalue2",
   "second2":"secondvalue2"
  }
}

我知道如何从对象 "first" (firstvalue) 和 second (secondvalue) 中检索数据,但我想循环遍历该对象并获取值:"hello" 和 "hello2"...

这是我的 PHP 代码:

<?php 

$jsonData='{"hello":{"first":"firstvalue","second":"secondvalue"},"hello2":{"first2":"firstvalue2","second2":"secondvalue2"}}';
$jsonData=stripslashes($jsonData);
$obj = json_decode($jsonData);

echo $obj->{"hello"}->{"first"}; //result: "firstvalue"
?>

可以吗?

【问题讨论】:

    标签: php json


    【解决方案1】:

    解码后的 JSON 应该会得到这种对象:

    object(stdClass)[1]
      public 'hello' => 
        object(stdClass)[2]
          public 'first' => string 'firstvalue' (length=10)
          public 'second' => string 'secondvalue' (length=11)
      public 'hello2' => 
        object(stdClass)[3]
          public 'first2' => string 'firstvalue2' (length=11)
          public 'second2' => string 'secondvalue2' (length=12)
    

    (您可以使用var_dump($obj); 获取)

    即你得到一个对象,hellohello2 作为属性名称。


    这意味着这段代码:

    $jsonData=<<<JSON
    {
     "hello":
      {
       "first":"firstvalue",
       "second":"secondvalue"
      },
      "hello2":
      {
       "first2":"firstvalue2",
       "second2":"secondvalue2"
      }
    }
    JSON;
    $obj = json_decode($jsonData);
    
    foreach ($obj as $name => $value) {
        echo $name . '<br />';
    }
    

    会得到你:

    hello
    hello2
    


    这将起作用,因为foreach 可用于迭代对象的属性——请参阅Object Iteration,关于这一点。

    【讨论】:

      猜你喜欢
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2012-09-20
      相关资源
      最近更新 更多