Foreach PHP problems to read Json

Asked

Viewed 123 times

-1

I am trying to get the values of the items (code and price) as follows in Json below:

 {
      "statusCode": 200,
      "message": "Ok",
      "description": "Requisição realizada com sucesso",
      "data": [
        {
          "nomePromocao": "teste de voucher",
          "dtaInicio": "2019-03-19T00:00:00",
          "itens": [
            {
              "codigo": "957",
              "preco": 9
            },
            {
              "preco": 0,
              "quantidade": 12
            },
            {
              "preco": 0
            },
            {
              "familia": 4,
              "preco": 12,
              "quantidade": 2
            }
          ]
        }, segue o próximo produto
   

{
  "nomePromocao": "Mês dos Achocolatados",
  "dtaInicio": "2019-03-31T00:00:00",
  "dtaFim": "2019-04-30T00:00:00",
  "itens": [
    {
      "codigo": "7896283514142",
      "preco": 12.3
    },
    {
      "codigo": "7891000387603",
      "preco": 11.2
    },
    {
      "codigo": "7894321711317",
      "preco": 11.3
    }
  ]
},

My PHP code:

$jsonStr = file_get_contents($url);
$jsonArr = json_decode($jsonStr, true);

$nome = array();
$data = array();
$itens = array();

foreach(($jsonArr["data"]) as $valor){
    echo $nome[] = $valor["nomePromocao"] . '</br>';
    echo $data[] = $valor["dtaInicio"] . '</br>';
    echo $itens[] = $valor["itens"]["codigo"] . '</br>';
}

In the items it returns me an error

test voucher 2019-03-19T00:00:00

Notice: Undefined index: codigo in C: xampp htdocs teste promocao.php on line 20

what the error of my foreach to reach the code and other information?

If I try like this:

foreach(($jsonArr["data"]) as $valor){
    echo $nome[] = $valor["nomePromocao"] . '</br>';
    echo $data[] = $valor["dtaInicio"] . '</br>';
    echo $itens[] = $valor["itens"][0]["codigo"] . '</br>';
    echo $itens[] = $valor["itens"][1]["preco"] . '</br>';
}

it only brings the first value.. I cannot advance

  • 1

    All items have code? Error says some item does not have code index.

  • Some do not have, but for example, just below there is an item that has 3 codes and only the first appears.. I will update my question

  • You need a foreach to traverse $jsonArr["data"] and another to travel $jsonArr["data"][N]["items"]... And it seems to me that you do not need to "reorganize" the structure that came from the API, because it is already adequate. You seem to be complicating the structure to do something you didn’t explain in the question.

1 answer

3


The problem happens for two reasons:

  1. Why you are not iterating the "items" but only the "date" index".

  2. Because the index "code" does not exist in all items.

To solve the first problem, a second foreach must be added to the "items".

To solve the second problem, you should check for the existence of the index "code" using "isset()".

You should modify your code a little to solve this:

$jsonArr = json_decode($jsonStr, true);

$nome = array();
$data = array();
$itens = array();

foreach(($jsonArr["data"]) as $valor){

    $nome[] = $valor["nomePromocao"];
    $data[] = $valor["dtaInicio"];

    foreach($valor["itens"] as $indice => $item){
        if (isset($item["codigo"])) {
            $itens[] = $item["codigo"];
        }

    }

}

var_dump($nome, $data, $itens);

The result will be:

/var/www/stackoverflow/question.php:54:
array (size=2)
  0 => string 'teste de voucher 1' (length=20)
  1 => string 'teste de voucher 2' (length=20)
/var/www/stackoverflow/question.php:54:
array (size=2)
  0 => string '2019-03-19T00:00:00' (length=21)
  1 => string '2019-03-19T00:00:00' (length=21)
/var/www/stackoverflow/question.php:54:
array (size=2)
  0 => string '957' (length=3)
  1 => string '959' (length=3)

I hope I’ve helped you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.