php:将多个数组值组合成一个数组保留键

php: combine multiple arrays value into one array preserving keys

我有多个结构如下的数组:

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

意思是:

我需要以最终结果类似这样的方式组合这些数组:

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

意思是:

我知道它有点乱,但我希望它足够清晰。我正在努力构建 $result 数组。我尝试了合并、组合、相交,但其中 none 似乎有效。有没有一种方法可以不使用循环来构建 $result 数组?

谢谢

它符合您的目标吗?

<?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);
?>

产出

Array
(
    [aaa] => Array
        (
            [0] => 1
            [1] => 12
        )

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

    [ccc] => 15
)

将所有数组合并为一个mergedArray。然后用2foreach设置。

<?php

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

$mergedArray = [$array1, $array2, $array3];


$result = [];
foreach ($mergedArray as $array) {
    foreach ($array as $key => $item) {
        $result[$key][] = $item;
    }
}

echo '<pre>';
print_r($result);
echo '</pre>';
exit;

?>

结果:

Array
(
    [aaa] => Array
        (
            [0] => 1
            [1] => 12
        )

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

    [ccc] => Array
        (
            [0] => 15
        )

)