简体   繁体   中英

How to get value by key from multidimensional array from an object attribute as number in PHP

How to get value by key from the multidimensional array in PHP

We Get TradeID in foreach loop

We get TradeID by Loop one by one

stdClass Object
    (
        [0] => 
        [1] => 1
        [2] => Array
            (
                [0] => Array
                    (
                        [TradeID] => 15950315
                        [Price] => 0.00000170
                        [Type] => buy
                        [Amount] => 712.85989430
                        [Total] => 0.00121368
                        [Time] => 1535337908
                    )

                [1] => Array
                    (
                        [TradeID] => 15908375
                        [Price] => 0.00000300
                        [Type] => buy
                        [Amount] => 574.71264368
                        [Total] => 0.00172673
                        [Time] => 1535022882
                    )
            )
    )

You need to use foreach twice.

PHP Code:

/* Generating structure */
$rawdata = array(
        '',
        1,
        array(
            array(
                'TradeID' => 15950315,
                'Price' => 0.00000170,
                'Type' => 'buy',
                'Amount' => 712.85989430,
                'Total' => 0.00121368,
                'Time' => 1535337908,
            ),
            array(
                'TradeID' => 15908375,
                'Price' => 0.00000300,
                'Type' => 'buy',
                'Amount' => 574.71264368,
                'Total' => 0.00172673,
                'Time' => 1535022882,
            )
        )
    );
$data = (object)$rawdata;
print_r($data);// same output as shown in the question


/** Getting TradeID */

foreach ($data as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $tradeKey => $tradevalue) {
            echo $tradevalue['TradeID'].'<br/>';
        }
    }
}

Please check output at: https://3v4l.org/d3KbN

Considering the $object variable would be the object you see, and only the first layer is an object, you can cast to an array using the notation (array) and continue the logic that you probably know already:

$array = (array) $object;

foreach ($array['2'] as $item) {
    echo $item['TradeID'];
}

Sorry for the previous answer, this one is fixed and tested here: https://3v4l.org/LOYtp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM