Search code examples
phparraysarray-merge

Combine elements within the array


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.


Solution

  • You'll have to make a map of keys that have to be grouped with another key ($group_keys in the code below)

    $test= [
        'EW' => [313, 1788], 
        'SC' => [670, 860], 
        'FR' => [704, 709], 
        'UK' => [423, 1733]
    ];
    
    $group_keys=[
        'EW' => 'UK', 
        'SC' => 'UK'
    ];
    
    $result = [];
    foreach($test as $code => $values) {
        if (isset($group_keys[$code])) {
            $target = $group_keys[$code];
        }
        else {
            $target = $code;
        }
        if (isset($result[$target])) {
            $result[$target] = array_merge($result[$target], $values);
        }
        else {
            $result[$target] = $values;
        }
    }
    
    print_r($result);
    

    Output:

    Array
    (
        [UK] => Array
            (
                [0] => 313
                [1] => 1788
                [2] => 670
                [3] => 860
                [4] => 423
                [5] => 1733
            )
    
        [FR] => Array
            (
                [0] => 704
                [1] => 709
            )
    
    )