I have multiple arrays structured like these:
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
meaning:
- every array has the same value for each key (eg: array1 has value "1" for every item in the array) but there are no arrays sharing the same value (eg: if array1 has value 1, then none of the other arrays has value = 1)
- the arrays may or may not share the same keys
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:
- the final array must contain all the keys from the previous arrays
- the value of the key is an array composed of all the values of the previous arrays that shared the same key
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
CodePudding user response:
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
)
CodePudding user response:
Merge all of array into an mergedArray
. Then use 2 foreach
to set it.
<?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;
?>
The result:
Array
(
[aaa] => Array
(
[0] => 1
[1] => 12
)
[bbb] => Array
(
[0] => 1
[1] => 12
[2] => 15
)
[ccc] => Array
(
[0] => 15
)
)