I am working with an array that is multi-dimensional and contains a nested array. The array has a duplicate and I would like to merge the array so that the array within each of the duplicate keys are combined into one.
Here is an example of the array:
$showTimes = array(
array(
'day' => 'Monday',
'details' => array(
array(
'theater' => 'Theater 1',
'times' => '1:00, 7:00, 8:00'
)
)
),
array(
'day' => 'Tuesday',
'details' => array(
array(
'theater' => 'Theater 1',
'times' => '2:00, 5:00'
)
)
),
array(
'day' => 'Tuesday',
'details' => array(
array(
'theater' => 'Theater 2',
'times' => '4:00, 9:00'
)
)
),
array(
'day' => 'Wednesday',
'details' => array(
array(
'theater' => 'Theater 1',
'times' => '1:00, 7:00, 8:00'
)
)
)
);
I would like to combine the two instances of Tuesday
so that the theaters and show times for that day both exist within a single instance. I have found some similar questions, but nothing with the depth of my array. From what I’ve seen it has to do with using the array key but I am completely lost. Here’s where I’m currently at:
$new_array = array();
foreach ($showTimes as $subArray) {
foreach ($subArray as $key=>$value) {
$new_array['details'][$key] = $value;
}
}
print_r($new_array);
The desired output would look like this:
Array
(
[0] => Array
(
[day] => Monday
[details] => Array
(
[0] => Array
(
[theater] => Theater 1
[times] => 1:00, 7:00, 8:00
)
)
)
[1] => Array
(
[day] => Tuesday
[details] => Array
(
[0] => Array
(
[theater] => Theater 1
[times] => 2:00, 5:00
)
[1] => Array
(
[theater] => Theater 2
[times] => 4:00, 9:00
)
)
)
[2] => Array
(
[day] => Wednesday
[details] => Array
(
[0] => Array
(
[theater] => Theater 1
[times] => 1:00, 7:00, 8:00
)
)
)
)
2
Answers
I built this out for fun … I believe it does what you are asking …
The output should look like:
With a foreach loop:
The equivalent with array_reduce: