How to group array of JSON objects with PHP

Asked

Viewed 222 times

0

I am receiving a JSON string from an API, to display the data I am converting the JSON string to php object, but my question is whether it is possible to group these objects, for example group all clients with the name X. As if it were the SQL group by.

API request code:

<?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>";

}

?>

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}

var_dump(customers):

array(1) { [0]=> object(stdClass)#1 (7) { ["id"]=> float(101800) ["pessoa.nome"]=> string(44) "Giovani" ["pessoaId"]=> string(5) "79271" ["totalHoraTrabalhada"]=> string(0) "" ["valorTotalOriginal"]=> string(4) "2,93" ["proprietario.nome"]=> string(13) "Gustavo Souza" ["proprietarioId"]=> string(4) "3940" } }
  • could post variable var_dump $clients?

  • Thanks for the reply, I added the return of var_dump in the post

  • tries to foreach with the $clientes->rows

No answers

Browser other questions tagged

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