-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
All items have code? Error says some item does not have code index.
– Leonardo Barros
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
– Ricardo Gonçalves
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.– fernandosavio