2

I have an array ($myArray) which looks like

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  ) )

I loop though the content for the values of Date using

array_walk_recursive($myArray, function($v, $k){
  if ($k == "Date") echo $v . PHP_EOL;

This would get me the correct output.

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

I want to add the output into an array and even if the value is null (ie[1] above) to still set an empty array.

For example $newArray =

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

Array ( )
Array ( [0] => 2018-05-13 [1] => 1991-03-29 )
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
jumpman8947
  • 571
  • 1
  • 11
  • 34
  • Do you need this to be flexible on the depth of the arrays (how nested they are within each other), or is the structure as shown; an outer array containing arrays that contain the arrays with named keys? – salathe Sep 05 '17 at 17:47
  • The structure is pretty much the same. some inner arrays are open, some may have up to X amount for entries with "Date" – jumpman8947 Sep 05 '17 at 17:52

2 Answers2

2

Given your example, an option is to use array_column() on each of the items in the outermost array, which is easy with the array_map() function.

$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);

The above will output something like:

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

    [1] => Array
        (
        )

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

)
salathe
  • 51,324
  • 12
  • 104
  • 132
0

You'll need to do a normal foreach loop for the top-level, and then use array_walk_recursive for the nested arrays.

$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

Barmar
  • 741,623
  • 53
  • 500
  • 612