php foreach group elements with the same value -
i have array looks 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 want group these elements in table row if same id value:
12 | no data, wrong format, no data 13 | not found, wrong name, no data i know have use foreach 1 logic grouping these elements in single row beyond me. appreciated. in advance. i've started this.
foreach($a $value){ echo $value['id'] . ' ' . $value['reason']; }
first group elements subarrays, output each subarray:
$groups = []; foreach($a $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 $key => $value) { echo $key . ' | ' . implode(', ', $value); // update echo $key . ' | ' . implode(', ', $value['names']) . ' | ' . implode(', ', $value['reasons']); }
Comments
Post a Comment