how to parse a json return with complex object

2

How do I parse a json return where I have optional fields such as phone, the user can have more than one such as residential, mobile and phone to message, in this case if the user has informed the phone it list if I have not informed it does not list any or only one or two, follow the example of a return below.

{
     "transacao":{
        "codigo":1,
        "nome":"bruno",
        "sobrenome":"richart",
        "idade":28,
        "endereco":{
           "rua":"Avenidas das Americas",
           "numero":12300,
           "bairro":"Barra da Tijuca",
           "cidade":"Andradina",
           "uf":"rj"
        },
        "telefone":[
           {
              "tipo":"residencial",
              "ddd":18,
              "numero":37236207
           },
           {
              "tipo":"celular",
              "ddd":18,
              "numero":972770022
           }
        ],
        "compra":{
           "idproduto":23,
           "descricao":"Celular Iphone",
           "quantidade":1
        }
     }
  }
    
asked by anonymous 14.11.2016 / 18:30

2 answers

2

To identify a phone key in this array would be:

//cria um array associativo quando segundo paramentro é true
$array = json_decode($json, true); 
//retorna true se a chave existir
array_key_exists('telefone', $array['transacao']);

the code:

$array = json_decode($json, true);
if (array_key_exists('telefone', $array['transacao']))
{
    foreach($arr['transacao']['telefone'] as $telefone)
    {
        echo $telefone['tipo'];
        echo $telefone['ddd'];
        echo $telefone['numero'];           
    }
}

References:

This avoids making mistakes.

    
14.11.2016 / 19:05
2

Just use json_decode($json,true) this way you will create an associative array.

Example:

<?php
        $json = '{
     "transacao":{
        "codigo":1,
        "nome":"bruno",
        "sobrenome":"richart",
        "idade":28,
        "endereco":{
           "rua":"Avenidas das Americas",
           "numero":12300,
           "bairro":"Barra da Tijuca",
           "cidade":"Andradina",
           "uf":"rj"
        },
        "telefone":[
           {
              "tipo":"residencial",
              "ddd":18,
              "numero":37236207
           },
           {
              "tipo":"celular",
              "ddd":18,
              "numero":972770022
           }
        ],
        "compra":{
           "idproduto":23,
           "descricao":"Celular Iphone",
           "quantidade":1
        }
     }
  }';


$arr = json_decode($json,true);

foreach($arr['transacao']['telefone'] as $telefone){
    print_r($telefone);
}

See working at: PHPSandbox

    
14.11.2016 / 18:43