Home > Software design >  Consolidate single multi-dimensional array by individual key of nested array PHP
Consolidate single multi-dimensional array by individual key of nested array PHP

Time:09-23

The question makes this sound way more complicated than it is. I have poured too much time into trying every variation of array_merge, etc. Maybe this is easy for someone:

I have a multi-dimensional array:

$array = [
        0 => [
            'class' => 'A',
            'jon' => '0.50'
        ],
        1 => [
            'class' => 'B',
            'jon' => '0.40'
        ],
        2 => [
            'class' => 'A',
            'steve' => '0.90'
        ],
        3 => [
            'class' => 'B',
            'steve' => '0.80'
        ]
    ];

The keys (0,1,2,3) aren't important. I want to consolidate this array based on the class key within each nested array. Desired outcome:

$outcome = [
        0 => [
            'class' => 'A',
            'jon' => '0.50',
            'steve' => '0.90'
        ],
        1 => [
            'class' => 'B',
            'jon' => '0.40',
            'steve' => '0.80'
        ]
    ];

Working in PHP7.4 if relevant, but I doubt it. Thanks in advance.

CodePudding user response:

Something like this would probably work.

$sorted = [];
foreach ($array as $item) {
    $sorted[$item['class']] = array_merge($item, $sorted[$item['class']] ?? []);
}
  • Iterating each item and plucking out the class property to make the key of the array
  • We then either merge the elements already attached to that key with the current item or thanks to the null coalescing operator - use an empty array
  • Related