What is the elegant way to read this PHP Object?

Asked

Viewed 1,041 times

4

I have the Result of a Webservice below, I’m doing a "foreachs" to read each level of the Class, but I think it should have a more elegant way to read and get the values of the object, follows the Result:

stdClass Object
(
    [Codigo] => 1-0-21
    [Descricao] => REGIONAL DDD21
    [DddArray] => stdClass Object
        (
            [string] => 21
        )

    [Valores] => stdClass Object
        (
            [Valor] => Array
                (
                    [0] => stdClass Object
                        (
                            [ValorFace] => 1000
                            [ValorBonus] => 0
                            [Produto] => RECARGA CELULAR
                        )

                    [1] => stdClass Object
                        (
                            [ValorFace] => 1500
                            [ValorBonus] => 0
                            [Produto] => RECARGA CELULAR
                        )

                    [2] => stdClass Object
                        (
                            [ValorFace] => 2000
                            [ValorBonus] => 0
                            [Produto] => RECARGA CELULAR
                        )


                )

        )

)

This text is the result of the function:

$res = $client->RetornaRegionaisPorOperadoraDdd($params);

The way I’m doing it is very "POG":

foreach ($res as $key => $value){
    foreach ($value as $keyopera => $valopera){
        print_r($valopera);
    }
}
  • 1

    There is nothing wrong with what you presented. Nor can I say that it is a Pog.. rsrs ..

  • 1

    POG is Gambarra Oriented Programming. Foreach it’s an elegant way.

  • 1

    A Gambiarra can contain a foreach() normally and continue to be a gambiarra.

  • 1

    Yes, the way he did it was Vida Loka.

  • This did not generate error? if you are iterating $res, $key could be Codigo, ai $value will not take an array.

1 answer

7


The simplest way is to indicate which key you want to iterate, thus electing the second foreach.

$res = $client->RetornaRegionaisPorOperadoraDdd($params);
foreach ($res->valores->valor as $item){
   echo $item['Produto'] .' - '. $item['ValorFace'];
}
  • Killed the stick rray, see how it turned out foreach ($res->RetornaRegionaisPorOperadoraDddResult->Regional->Valores->Valor as $item){
 echo $item->Produto .' - '. $item->ValorFace;
}

Browser other questions tagged

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