phparraysarray-combine

php: combine multiple arrays value into one array preserving keys


I have multiple arrays structured like these:

$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];

meaning:

I need to combine these arrays in a way that the final result is something like this:

$result = [
    "aaa" => [1,12],
    "bbb" => [1,12,15],
    "ccc" => [15],
];

meaning:

I know it's a bit messy, but I hope it is clear enough. I'm struggling to build the $result array. I tried merge, combine, intersect, but none of them seems to work. Is there a way to build the $result array without using a loop?

Thanks


Solution

  • Does it match your goal ?

    <?php
        $array1 = ["aaa" => 1, "bbb" => 1];
        $array2 = ["aaa" => 12, "bbb" => 12];
        $array3 = ["bbb" => 15, "ccc" => 15];
    
        $array = array_merge_recursive($array1, $array2, $array3);
        
        print_r($array);
    ?>
    

    outputs

    Array
    (
        [aaa] => Array
            (
                [0] => 1
                [1] => 12
            )
    
        [bbb] => Array
            (
                [0] => 1
                [1] => 12
                [2] => 15
            )
    
        [ccc] => 15
    )