PHP JSON veri alma

1 Cevap php

Ben böyle bir JSON veri var:

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

I (ilkDeger) ve ikinci (secondvalue) "ilk" nesne verileri almak nasıl biliyorum ama döngü Zati bu nesneyi istiyorum ve bunun sonucunda değerler olsun: "merhaba" ve "hello2" ...

Bu benim PHP kodu:

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

Bu yapılabilir mi?

1 Cevap

JSON, deşifre edildikten sonra, size nesne bu tür almak gerekir:

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); bunu elde etmek için)

yani hello ve hello2 özellikleri adları gibi olan, bir nesne alıyoruz.


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

Alacak:

hello
hello2


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