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',
)
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
array_column()doesn't need to check if the column key exists to avoid warningsCheck leaf-node keys recursively (not recommended)
array_walk_recursive()traverses leaf-nodes and 'Data' is always "scalar", allDateelements will be foundarray_walk_recursiveis level-ignorantarray_walk_recursive()traverses leaf-nodes, it will visit ALL scalar elements in the structure which means there will be some useless processingDatechanges to something iterable, then it ceases to be a leaf-nodeLoop and push elements columns using the spreading operator
$resultvariable must be declaredClassic nested foreach loops
$resultvariable to be declaredarray_key_exists()will not be necessary if the input data is guaranteed to contain theDateelement on all levels. If they are not guaranteed to exist, then the condition serves to prevent warnings.A modern spin on classic nested loops
$resultvariable to be declaredforeach()as well as a body-less loop pushing data into a variable so your development team may not be familiar with the syntax.Dateelement must exist on all levels.