Search code examples
phparraysapiobjectstdclass

Get value of array stdClass Object


I am performing an insertion of values ​​using an api. then, I send the values ​​correctly and get the return on the same page. Eg:

<?php
...
$return= $set->createCharge([
   'description'    => 'Strings etc...',
   'amount'     => 10.0
)];

print_r($return);

?>

This print_r Result is:

stdClass Object
(
[data] => stdClass Object
    (
        [charges] => Array
            (
                [0] => stdClass Object
                    (
                        [code] => 555
                        [reference] => 66
                        [dueDate] => 23/11/2020
                        [checkoutUrl] => https://url/number_return
                        [link] => https://url_return
                        [installmentLink] => https://url
                        [payNumber] => 9999999999
                        [billetDetails] => stdClass Object
                            (
                                [bankAccount] => 888888
                                [ourNumber] => 12121-9
                                [barcodeNumber] => 0541454141411141414141414
                                [portfolio] => 0001
                            )

                    )

            )

    )

[success] => 1

)

I tried to get the value '[code'] using the following:

echo $return[0]['code'];//Dont work

echo $return['data']['charges'][0]['code'];//Dont Work

how can I get the value of [code] or another that is in that array?


Solution

  • Each element in the "charges" array is an object. A different syntax is used to refer to the members of the object:

    //for an array
    echo $someArray['someValue'];
    
    //for an object
    echo $someObject->someValue;
    echo $someObject->getSomeValue()
    

    Therefore, this is the way for you:

    echo $return->data->charges[0]->code;
    
    

    Or, step by step:

    var_dump($return);
    var_dump($return->data);
    var_dump($return->data->charges);
    var_dump($return->data->charges[0]);
    var_dump($return->data->charges[0]->code);
    var_dump($return->data->charges[0]->code->billetDetails);
    var_dump($return->data->charges[0]->code->billetDetails->bankAccount);