簡體   English   中英

在PHP中獲取JSON數據

[英]Getting JSON data in PHP

我有一個像這樣的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"
?>

能做到嗎

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來迭代對象的屬性-有關此信息,請參見對象迭代

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM