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:
function array_merge_trees($original)
// Merge individual trees within an array.
{
$mergeme=array(UK, EW, SC, NI, DE, ES, FR, IT); //The trees you want to merge. IMPORTANT: The trees must exist within the original array, or you will get empty trees in the joined array.
$trim=array_flip($mergeme); // Convert the $mergeme values to keys.
extract(array_intersect_key($original, $trim)); // Extract the trees in $mergeme - they will each become an array named after the key, eg $UK, $EW.
$merged['UK']=array_merge($UK, $EW, $SC, $NI); // Merge extracted trees as an element of a new array. IMPORTANT: The trees listed here must exist within the original array, or you will get empty trees in the joined array.
sort($merged['UK']); // Sort the values of the merged tree.
// Repeat the above two lines if you want further merges, eg:
$merged['EU'] = array_merge($DE, $ES, $FR, $IT);
sort($merged['EU']);
$trimmed=array_diff_key($original, $trim); // Remove the trees to be merged from the original array.
$rejoined=array_merge($trimmed, $merged); // Join the merged trees with the non-merged trees from the original array.
ksort($rejoined); // Sort the keys of the rejoined array.
return $rejoined;
}
To use it:
$original=array("EW"=>array(313, 1788), "SC"=>array(670, 860), "FR"=>array(704, 709), "UK"=>array(423, 1733), "DE"=>array(220, 260), "ES"=>array(1346, 1229), "NI"=>array(410, 453), "IT"=>array(134, 988));
$original=array_merge_trees($original);
echo "<pre>";
print_r($original);
echo "</pre>";
EDIT: Honk's answer is much better than this one.