如何通过PHP多维数组通过键获取价值
我们在foreach循环中获取TradeID
我们逐一循环获取TradeID
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
)
)
)
答案 0 :(得分:1)
您需要两次使用foreach。
PHP代码:
/* 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/>';
}
}
}
请在以下位置检查输出:https://3v4l.org/d3KbN
答案 1 :(得分:-1)
考虑到$object
变量将是您看到的对象,并且只有第一层是一个对象,您可以使用符号(array)
强制转换为数组,并继续您可能已经知道的逻辑:
$array = (array) $object;
foreach ($array['2'] as $item) {
echo $item['TradeID'];
}
很抱歉,上一个答案已在此处修复并测试:https://3v4l.org/LOYtp