Skip to content
Advertisement

Group rows on one column and create nested array from another column

I have an array that looks like this:

[
    [
        'name' => 'Umber',
        'reason' => 'No data',
        'id' => '12'
    ],
    [
        'name' => 'Jakar',
        'reason' => 'Wrong format',
        'id' => '12'
    ],
    [
        'name' => 'Lane',
        'reason' => 'No data',
        'id' => '12'
    ],
    [
        'name' => 'Jake',
        'reason' => 'Not found',
        'id' => '13'
    ],
    [
        'name' => 'Jame',
        'reason' => 'Wrong name',
        'id' => '13'
    ],
    [
        'name' => 'Joe',
        'reason' => 'No data',
        'id' => '13'
    ]
];

What I want to do is group these elements in a table row if the same id value:

12 | No data, wrong format, No data
13 | Not found, Wrong name, No data

I know I have to use foreach for this one but the logic for grouping these elements in a single row is beyond me. Any help would be appreciated. Thanks in advance. I’ve started with this.

foreach($a as $value){
    echo $value['id'] . ' ' . $value['reason'];
}

Advertisement

Answer

First group elements to subarrays, then output each subarray:

$groups = [];
foreach($a as $value){
    $groups[$value['id']][] = $value['reason'];
}

foreach ($groups as $key => $value) {
    echo $key . ' | ' . implode(', ', $value);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement