I have the following array which represents a working schedule:
Array
(
...,
[1] => Array
(
[TIME] => Array
(
[0] => Array
(
[FROM] => 10:00
[TO] => 20:00
)
)
[DAYS] => Array
(
[0] => 5
)
)
[2] => Array
(
[TIME] => Array
(
[0] => Array
(
[FROM] => 22:00
[TO] => 00:00
)
)
[DAYS] => Array
(
[0] => 5
)
)
)
What I would like to do is to combine (or merge?) array columns if DAYS key is common so the result would look like this:
Array
(
...,
[1] => Array
(
[TIME] => Array
(
[0] => Array
(
[FROM] => 10:00
[TO] => 20:00
)
[1] => Array
(
[FROM] => 22:00
[TO] => 00:00
)
)
[DAYS] => Array
(
[0] => 5
)
)
)
I used to try array_merge() and array_combine() functions but they didn’t work as I thought they should.
Will appreciate any help!
>Solution :
So something i tried with your given input and output, assuming Days just has one value, correct?
$schedules =
[
[
'TIME' =>
[
[
"FROM" => "10:00",
"TO" => "20:00"
]
],
'DAYS' => [5]
],
[
'TIME' =>
[
[
"FROM" => "22:00",
"TO" => "00:00"
]
],
'DAYS' => [5]
]
];
$hashmap = [];
foreach ($schedules as $schedule) {
$days = $schedule['DAYS'][0];
if (!isset($hashmap[$days])) {
$hashmap[$days] = $schedule;
} else {
$hashmap[$days]['TIME'] = array_merge($hashmap[$days]['TIME'], $schedule['TIME']);
}
}
$hashmap = array_values($hashmap);
Hope this helps