存储来自多维数组的列数据,同时保留缺少的元素

时间:2017-09-05 17:33:09

标签: php multidimensional-array array-column

我有一个类似

的数组($myArray
Array ( [0] => 
   Array ( [0] => 
      Array ( 
         [Date] => 1776-08-08
         [Color] => Yellow 
         [Description] => Rotten
       ) ) 

    [1] => Array ( ) 
    [2] => 
     Array ([0] =>
      Array ( 
       [Date] => 2018-05-13 
       [Color] => Red 
       [Status] => Fresh 
      ) 
         [1] => 
      Array ( 
       [Date] => 1991-03-29
       [Color] => Green 
       [Status] => Fresh  ) )

我使用

循环查看Date值的内容
array_walk_recursive($myArray, function($v, $k){
  if ($k == "Date") echo $v . PHP_EOL;

这会让我得到正确的输出。

1776-08-08 2018-05-13 1991-03-29

我想将输出添加到数组中,即使值为null(即上面的[1])仍然设置一个空数组。

例如$ newArray =

Array ( [0] => 1776-08-08 )

Array ( )
Array ( [0] => 2018-05-13 [1] => 1991-03-29 )

2 个答案:

答案 0 :(得分:2)

根据您的示例,一个选项是对最外层数组中的每个项使用array_column(),使用array_map()函数很容易。

$input = array(
    array(
        array(
            "Date" => "1776-08-08",
            "Color" => "Yellow",
            "Description" => "Rotten",
        ),
    ),
    array(
    ),
    array(
        array(
            "Date" => "2018-05-13",
            "Color" => "Red",
            "Status" => "Fresh",
        ),
        array(
            "Date" => "1991-03-29",
            "Color" => "Green",
            "Status" => "Fresh",
        ),
    ),
);

$output = array_map(function($sub_arrays) {
    return array_column($sub_arrays, "Date");
}, $input);

print_r($output);

以上将输出如下内容:

Array
(
    [0] => Array
        (
            [0] => 1776-08-08
        )

    [1] => Array
        (
        )

    [2] => Array
        (
            [0] => 2018-05-13
            [1] => 1991-03-29
        )

)

答案 1 :(得分:0)

您需要为顶层执行正常foreach循环,然后使用array_walk_recursive作为嵌套数组。

$newArray = array();
foreach ($myArray as $el) {
    $temp = array();
    array_walk_recursive($el, function($v, $k) use (&$temp) {
            if ($k == "Date") {
                $temp[] = $v;
            }
        });
    $newArray[] = $temp;
}

DEMO