I have no idea why this question has been marked as a duplicate, because the so-called duplicate is about using array_merge
to combine arrays – this question is about combining element trees WITHIN an array.
Is there a way to combine individual elements and their subtrees within a PHP array? For instance, to convert this:
$test = array(
"EW" => array(313, 1788),
"SC" => array(670, 860),
"FR" => array(704, 709),
"UK" => array(423, 1733)
);
into this:
$test1 = array(
"UK" => array(313, 423, 670, 860, 1733, 1788),
"FR" => array(704, 709)
);
where the entries for EW and SC have been combined with those for UK.
array_combine
and array_merge
seem to work between arrays, not within them, so I’m not clear how to approach this.
3
Answers
The function {array_merge_trees} will take an array, cut out the trees to be merged and merge them, remove them from the original array, and join the merged trees to what is left of the original array:
To use it:
EDIT: Honk's answer is much better than this one.
One way to do it will be like this:
The result:
For small use case where you know the key and it will not change this method is ok …
You’ll have to make a map of keys that have to be grouped with another key (
$group_keys
in the code below)Output: