开发者

Getting JSON data in PHP

开发者 https://www.devze.com 2022-12-24 05:38 出处:网络
I have a JSON data like this: { \"hello\": { \"first\":\"firstvalue\", \"second\":\"secondvalue\" }, \"hello2\":

I have a JSON data like this:

{
 "hello":
  {
   "first":"firstvalue",
   "second":"secondvalue"
  },
  "hello2":
  {
   "first2":"firstvalue2",
   "second2":"secondvalue2"
  }
}
开发者_开发技巧

I know how to retrieve data from object "first" (firstvalue) and second (secondvalue) but I would like to loop trough this object and as a result get values: "hello" and "hello2"...

This is my PHP code:

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

Can it be done?


The JSON, after being decoded, should get you this kind of object :

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)

(You can use var_dump($obj); to get that)

i.e. you're getting an object, with hello and hello2 as properties names.


Which means this code :

$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 />';
}

Will get you :

hello
hello2


This will work because foreach can be used to iterate over the properties of an object -- see Object Iteration, about that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号