2010-03-24 5 views
1

J'ai des données JSON comme ceci:Obtenir des données JSON en PHP

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

Je sais comment récupérer les données de l'objet « first » (firstValue) et deuxième (SecondValue), mais je voudrais creux LOOP objet et par conséquent obtenir des valeurs: "bonjour" et "hello2" ...

Voici mon code 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" 
?> 

peut-il être fait?

Répondre

3

Le JSON, après avoir été décodé, si vous obtenez ce genre d'objet:

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) 

(Vous pouvez utiliser var_dump($obj); pour obtenir que)

-à-dire que vous obtenez un objet, avec hello et hello2 comme noms de propriétés.


Ce qui signifie que ce 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 />'; 
} 

Est-ce que vous obtenez:

hello 
hello2 


Cela fonctionnera, car foreach peut être utilisé pour itérer sur les propriétés d'un objet - voir Object Iteration, à ce sujet.