2

我有一个数组($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 )
4

2 回答 2

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
        )

)
于 2017-09-05T17:55:13.077 回答
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;
}

演示

于 2017-09-05T17:36:17.400 回答