'Use subarray keys to form new first level keys to group values [duplicate]

I have an array $a in the below format. I have to separate the array and value with same key. For example first array have 9 and 10 key, last array 9 and 10. so both the array have to merge.

$a = [
    ['9' => 0, '10' => 5000],
    ['1' => -5000, '2' => 0],
    ['1' => -1600, '2' => 0],
    ['9' => 0, '10' => 5200],
];

need to convert the array like the below format

[
    '9' => [0, 0],
    '10' => [5000, 5200],
    '1' => [-5000, -1600],
    '2' => [0, 0]
]


Solution 1:[1]

You were in the right direction, you just needed the [] in front of $key to achieve your desired result, as shown below:

$samearray = array();
foreach ($a as $det) {
    foreach ($det as $key => $det1) {
        $samearray[$key][] = $det1;
    }
}

print_r($samearray);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haseeb Hassy