我有一个如下所示的数组:
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'
如果ID值相同,我想要做的是将这些元素分组到表格行中:
12 | No data, wrong format, No data
13 | Not found, Wrong name, No data
我知道我必须将foreach用于这个,但是将这些元素分组在一行中的逻辑超出了我的范围。任何帮助,将不胜感激。提前致谢。我已经开始了。
foreach($a as $value){
echo $value['id'] . ' ' . $value['reason'];
}
答案 0 :(得分:4)
第一组元素到子数组,然后输出每个子数组:
$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']);
}
答案 1 :(得分:1)
也许是这样的。它应该有助于您入门:
$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);
}