0
Greetings, I’m trying to request a JSON so I can attach each value in a variable, conduit, I’m getting the errors:
Notice: Trying to get Property 'product' of non-object in E: Rafael Desktop T.I Xamp htdocs litoralplace backend productshow.php on line 14
Warning: Invalid argument supplied for foreach() in E: Rafael Desktop T.I Xamp htdocs litoralplace backend productshow.php on line 14
My code:
<?php
$json_file = file_get_contents('produtos.json', true);
$codigo; $descricao; $tipo;
$json_str = json_decode($json_file);
foreach ($json_str->retorno->produtos->produto as $key) {
$codigo = $key->codigo;
$descricao = $key->descricao;
$tipo = $key->tipo;
}
?>
unfortunately I can not make available the.json products file as it has confidential company information. I will just exemplify it:
{
"retorno": {
"produtos": [
{
"produto": {
"codigo": "1",
"descricao": "Fonte Thermaltake 430W Smart Séries",
"tipo": "P"
},
"produto": {
"codigo": "2",
"descricao": "Processador AMD Ryzen 3 3200G",
"tipo": "P",
}
}
]
}
}
In JSON there are 100 Products, I am trying to insert in the variables only one product and its parameters. I’m sorry if you got a little confused, I really need this help.
Illustrating what I need: I need to take the values of each Product (code, description and type), and attach in an array. For example: Code array: Needs to be filled in with code 1 and 2. My question is not knowing how to differentiate these two "product" to gather their information, since JSON was formatted in this way via an API.
This json is incorrect
– adventistaam
complicated, it is the fruit of an API, came so already. How should I fix it?
– Antônio Ascot
Now, I’ve seen, you’ve got the wrong keys, I’ll fix it. Anyway, that bug isn’t really in my code.
– Antônio Ascot
Gives a
print_r($json_str); die;
and put the comeback.– Kayo Bruno
php
stdClass Object
(
 [retorno] => stdClass Object
 (
 [produtos] => Array
 (
 [0] => stdClass Object
 (
 [produto] => stdClass Object
 (
 [codigo] => 2
 [descricao] => Processador AMD Ryzen 3 3200G
 [tipo] => P
 )

 )

 )

 )

)

here friend– Antônio Ascot
Your
foreach
is to go up$json_str->retorno->produtos
.produto
is an item of the product array.– Kayo Bruno
got it!! Good, thank you very much. However, how should I differentiate and go through the indexed items each Product that is in the products array?
– Antônio Ascot
I’m sorry but I couldn’t understand what you want to do, please if possible edit the question and try to exemplify what you want to do.
– Kayo Bruno
I’ll do it. Thank you
– Antônio Ascot
I edited there, if you can take a look, thank you.
– Antônio Ascot