I have an array that looks like this:
array (size=6)
0 =>
array (size=3)
'name' => string 'Umber'
'reason' => string 'No data'
'id' => string '12'
1 =>
array (size=3)
'name' => string 'Jakar'
'reason' => string 'Wrong format'
'id' => string '12'
2 =>
array (size=3)
'name' => string 'Lane'
'reason' => string 'No data'
'id' => string '12'
3 =>
array (size=3)
'name' => string 'Jake'
'reason' => string 'Not found'
'id' => string '13'
4 =>
array (size=3)
'name' => string 'Jame'
'reason' => string 'Wrong name'
'id' => string '13'
5 =>
array (size=3)
'name' => string 'Joe'
'reason' => string 'No data'
'id' => string '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'];
}
First group elements to subarrays, then output each subarray:
$groups = [];
foreach($a as $value){
if (!isset($groups[$value['id']])) {
$groups[$value['id']] = [];
// update
$groups[$value['id']] = [
'names' => [],
'reasons' => [],
];
}
$groups[$value['id']][] = $value['reason'];
// update
$groups[$value['id']]['names'][] = $value['name'];
$groups[$value['id']]['reasons'][] = $value['reason'];
}
foreach ($groups as $key => $value) {
echo $key . ' | ' . implode(', ', $value);
// update
echo $key . ' | ' . implode(', ', $value['names']) . ' | ' . implode(', ', $value['reasons']);
}
Something like this, perhaps. It should help get you started:
$output = [];
foreach ($arrary as $arr) {
if (!isset($output[$arr['id']])) {
$output[$arr['id']] = [];
}
$output[$arr['id']][] = $arr['reason'];
}
foreach ($output as $k => $v) {
echo $k;
echo implode(',', $v);
}