phparraysmultidimensional-arraygroupingarray-merge

Group and merge subarray data based on one column value


I have an array in PHP code below, and I want to convert this array to be grouped by data value. It's always hard to simplify arrays.

Original array:

$array = [
    ['date' => '2017-08-22', 'AAA' => 1231],
    ['date' => '2017-08-21', 'AAA' => 1172],
    ['date' => '2017-08-20', 'AAA' => 1125],
    ['date' => '2017-08-21', 'BBB' => 251],
    ['date' => '2017-08-20', 'BBB' => 21773],
    ['date' => '2017-08-22', 'CCC' => 3750],
    ['date' => '2017-08-20', 'CCC' => 321750],
];

Below is my desired array:

[
    '2017-08-22' => ['AAA' => 1231, 'CCC' => 3750],
    '2017-08-21' => ['AAA' => 1172, 'BBB' => 251],
    '2017-08-20' => ['AAA' => 1125, 'BBB' => 21773, 'CCC' => 321750],
]

It is also ok to have empty null value if the data doesn't exist. [BBB] => NULL for 2017-08-22. Can anybody help? Thanks in advance...


Solution

  • A simple loop should do this..

    $group = [];
    foreach ($data as $item)  {
        if (!isset($group[$item['date']])) {
            $group[$item['date']] = [];
        }
        foreach ($item as $key => $value) {
            if ($key == 'date') continue;
            $group[$item['date']][$key] = $value;
        }
    }