Know the name of the object in JSON

4

I have a JSON and I need to know the name of my object and the values it has, for example:

    {"Pessoas" :
          [ 
           {"Nome": "Welson Play", "Idade":19}, 
           {"Nome": "Stephanie", "Idade":15},
           {"Nome": "João Pedro", "Idade":17}
          ] 
    }

I needed to get the code name Pessoas and the values that each person has, but this without knowing the name, for example, could be Animais , Carros . This is because my table in BD columns can vary, that is, I can browse JSON .

    
asked by anonymous 08.07.2015 / 13:11

1 answer

3

You can use a foreach to iterate this object.

For example:

$jsonstring = '{"Pessoas" :
      [ 
       {"Nome": "Welson Play", "Idade":19}, 
       {"Nome": "Stephanie", "Idade":15},
       {"Nome": "João Pedro", "Idade":17}
      ] 
}';

$obj = json_decode($jsonstring);

foreach($obj as $chave => $array) {
    echo $chave;    // dá "Pessoas"
    // fazer aqui o que fôr preciso com a array $array
}

Example: link

To read child object objects, ( nome , idade ....) it is necessary to continue to iterate. In the above example the array can be iterated and then the keys / value of each object.

In practice it takes two more loops:

foreach($obj as $chave => $array) {
    foreach($array as $index => $pessoa) {
        foreach($pessoa as $dado => $valor) {
            // neste nível estás dentro de cada objeto '{"Nome": "João Pedro", "Idade":17}' 
    
08.07.2015 / 13:29