phparraysloopsmultidimensional-arrayarray-column

Get column of data from third level of a multidimensional array


I have a multidimensional array with four levels of data. Here's a small sample:

$data = [
    [
        [
            'Date' => '2021-03-15T00:00:00.0000000+01:00',
            'Arena' => ['Id' => 181796, 'Name' => 'Motala bibliotek'],
            'Description' => null,
            'IsCanceled' => null
        ],
        [
            'Date' => '2021-03-16T00:00:00.0000000+01:00',
            'Arena' => ['Id' => 181796, 'Name' => 'Motala bibliotek'],
            'Description' => null,
            'IsCanceled' => null
        ],
        [
            'Date' => '2021-03-17T00:00:00.0000000+01:00',
            'Arena' => ['Id' => 181796, 'Name' => 'Motala bibliotek'],
            'Description' => null,
            'IsCanceled' => null
        ]
    ],
    [
        [
            'Date' => '2021-03-15T00:00:00.0000000+01:00',
            'Arena' => ['Id' => 181796, 'Name' => 'Motala bibliotek'],
            'Description' => null,
            'IsCanceled' => null
        ],
        [
            'Date' => '2021-03-16T00:00:00.0000000+01:00',
            'Arena' => ['Id' => 181796, 'Name' => 'Motala bibliotek'],
            'Description' => null,
            'IsCanceled' => null
        ]
    ]
];

I need to collect all of the Date values from the third level in the array.

I know how to loop through the top level, but I am at a loss for how to write the rest of the code to get the deeper Date elements.

for($i = 0; $i < count($data); $i++) {
    echo $i;
    echo "<br>";
}

Desired output:

array (
  0 => '2021-03-15T00:00:00.0000000+01:00',
  1 => '2021-03-16T00:00:00.0000000+01:00',
  2 => '2021-03-17T00:00:00.0000000+01:00',
  3 => '2021-03-15T00:00:00.0000000+01:00',
  4 => '2021-03-16T00:00:00.0000000+01:00',
)

Solution

  • There are several ways to extract a column of data from the third level of a multidimensional array. Different techniques will have trade-offs. The following demonstrations will all generate the same output. (Demo Link)

    Eliminate top level of structure with spread operator before isolating columns

    Check leaf-node keys recursively (not recommended)

    Loop and push elements columns using the spreading operator

    Classic nested foreach loops

    A modern spin on classic nested loops