【发布时间】:2020-01-01 22:51:12
【问题描述】:
我需要从多维数组中提取值。然而,起点是一个 stdClass 对象。目的是使用提取的值来创建图表。该图不是这个问题的一部分。
问题:
下面有没有更短更直接的方法? 请注意,这些值可以是 100,因此我不打算一一提取这些值。
// Create an stdClass.
$products = (object)[
'group' => [
['level' => "12"],
['level' => "30"],
['level' => "70"],
]
];
// Transform stdClass to array.
$products = json_decode(json_encode($products), true);
var_dump($products);
// Calc amount of subarrays.
$amount_of_subarrays = count($products['group']);
$amount_of_subarrays = $amount_of_subarrays - 1; // Adjust since objects start with [0].
// Extract data from [$products], populate new array [$array].
$array = [];
for ($i=0; $i <= $amount_of_subarrays; $i++) {
$tmp = $products['group'][$i]['level'];
array_push($array, $tmp);
}
var_dump($array);
结果(如预期):
array(3) {
[0] =>
string(2) "12"
[1] =>
string(2) "30"
[2] =>
string(2) "70"
}
【问题讨论】:
-
简而言之,并非如此。
foreach ($products->group as $group) { $array[] = $group["level"]; }尽可能简单。 -
array_column($products['group'], 'level'). -
@Jonnix。如果您将评论移至答案,我将继续批准答案。
标签: php arrays for-loop multidimensional-array