首页 > 解决方案 > 从多维数组中提取值并存储在单独的数组中

问题描述

我需要从多维数组中提取值。然而,起点是一个 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"
}

标签: phparraysfor-loopmultidimensional-array

解决方案


我知道的最简单的方法是使用返回的array_column函数the values from a single column in the input array

例如array_column($products['group'], 'level')应该返回预期的结果。


推荐阅读