0
I am in error when manipulating JSON data from an API, some fields I can even manipulate. I’m taking the responsibility of the API, converting to a PHP object with the json function Code the problem is that in this API, the client name is as "person.name" and when making a foreach to display the data of each client, an error appears saying that "name" has not been set.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.com.br/v1/entidades/HoraTrabalhada?campos=pessoa.nome,totalHoraTrabalhada,valorTotalOriginal,proprietario.nome&page&pageSize=100&criterio",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: ",
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$json_obj = json_decode($response);
$clientes = $json_obj->rows;
foreach ($clientes as $cliente) {
echo "Valor hora: $cliente->valorTotalOriginal - Cliente: " . $cliente->pessoa.nome . "<br />";
}
echo "<br />";
echo "<a href='index.php'><button>Voltar</button><a>";
}
?>
Error:
Notice: Undefined property: stdClass::$pessoa in C:\xampp\htdocs\apidatajuri\entidades.php on line 33
Warning: Use of undefined constant nome - assumed 'nome' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\apidatajuri\entidades.php on line 33
Valor hora: 0,00 - Cliente: nome
Notice: Undefined property: stdClass::$pessoa in C:\xampp\htdocs\apidatajuri\entidades.php on line 33
Warning: Use of undefined constant nome - assumed 'nome' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\apidatajuri\entidades.php on line 33
Valor hora: 0,00 - Cliente: nome
JSON received:
{"rows":[{"id":101448.0,"pessoa.nome":"Nome da pessoa","pessoaId":"79271","totalHoraTrabalhada":"","valorTotalOriginal":"5,86","proprietario.nome":"Nome da pessoa","proprietarioId":"4204"},{"id":101447.0,"pessoa.nome":"Nome da empresa","pessoaId":"74115","totalHoraTrabalhada":"","valorTotalOriginal":"8,79","proprietario.nome":"Nome da pessoa","proprietarioId":"4204"}],"listSize":51229.0,"modulo":"HoraTrabalhada","pageSize":2.0,"page":0.0}
$cliente->pessoa.nome
, here you are concatenating the value$cliente->pessoa
withnome
. This second, by default, will be considered as a string and launched the Warning which you have obtained by not being a definite constant. Could [Edit] the question with an excerpt from the received JSON?– Woss
I made the edit by displaying the received JSON.
– Gustavo Alves