【问题标题】:Extract values from multidimensional array and store in separate array从多维数组中提取值并存储在单独的数组中
【发布时间】: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-&gt;group as $group) { $array[] = $group["level"]; } 尽可能简单。
  • array_column($products['group'], 'level').
  • @Jonnix。如果您将评论移至答案,我将继续批准答案。

标签: php arrays for-loop multidimensional-array


【解决方案1】:

您不需要使用 json_encode 和 json_decode 从 stdClass 到数组的转换 如果使用这个:

$result = array_column($products->group, 'level');

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多