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.
2
Answers
So something I tried with your given input and output, assuming Days just has one value, correct?
As demonstrated in Group and merge related subarray data in multidimensional array: Consolidate related taxonomy array settings to be used in a WordPress query (I could not use this page as a dupe target because there are no upvoted answers), Create references on the first encountered instance of the "identifying data", then push that reference (containing the first instance’s data) into the result array. For any subsequent encounters of the same "identifying data", push the new subset’s data into the reference. Because this technique modifies the original (instead of creating a new array),
unset()
(consume) the later encountered instances.Code: (Demo)
Using
array_push()
merely appends the new data to the end of the indexed subarray instead of callingarray_merge()
.