Search code examples
phparraysmultidimensional-array

Simplify API response payload to a 2d array with standardized second level keys


I'm having trouble handling a nested array I get as result from an API. Print_r($result, true); returns an array looking like this (only much longer):

Array
(
    [success] => 1
    [return] => Array
        (
            [sellorders] => Array
                (
                    [0] => Array
                        (
                            [sellprice] => 0.00000059
                            [quantity] => 1076.00000000
                            [total] => 0.00063484
                        )

                    [1] => Array
                        (
                            [sellprice] => 0.00000060
                            [quantity] => 927.41519000
                            [total] => 0.00055645
                        )
                )

            [buyorders] => Array
                (
                    [0] => Array
                        (
                            [buyprice] => 0.00000058
                            [quantity] => 6535.77328102
                            [total] => 0.00379075
                        )

                    [1] => Array
                        (
                            [buyprice] => 0.00000057
                            [quantity] => 118539.39620414
                            [total] => 0.06756746
                        )
                )

        )

)

I need to grab the 3 values (sellprice/buyprice, quantity, total) from the first index of both arrays (sellorders and buyorders) and store them in variables ($sellprice, $sellquantity, $selltotal).

The full example php script I'm using can be found on the bottom of this page.


Solution

  • In php, arrays can more or less have infinite dimensions. You can go deeper within an array's dimensions by adding another set of square brackets. For example,

    $array['deep']['deeper']['deepest'][0];
    

    Assuming the indexes in the sellorders and buyorders are the same in your array, you could do

    $sellprice = $result['return']['sellorders'][0]['sellprice'];
    $sellquantity = $result['return']['sellorders'][0]['quantity'];
    $selltotal = $result['return']['sellorders'][0]['total'];