jumpman8947
jumpman8947

Reputation: 581

Store column data from a multidimensional array while preserving missing elements

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 )

Upvotes: 2

Views: 73

Answers (2)

Barmar
Barmar

Reputation: 781848

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

Upvotes: 0

salathe
salathe

Reputation: 51950

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
        )

)

Upvotes: 2

Related Questions