Skip to content

Instantly share code, notes, and snippets.

@ngekoding
Created September 12, 2023 03:52
Show Gist options
  • Save ngekoding/efa0c72c0acdd68631e49210641bded5 to your computer and use it in GitHub Desktop.
Save ngekoding/efa0c72c0acdd68631e49210641bded5 to your computer and use it in GitHub Desktop.
Grouping an array - specific case!
<?php
/**
* Grouping an array by `type` and `bank`,
* but when the `amount` is different for the same `name` (people)
* it must in another group
*/
echo '<pre>';
$array = [
['name' => 'John', 'amount' => 1000, 'type' => 1, 'bank' => 'BRI'],
['name' => 'John', 'amount' => 1000, 'type' => 1, 'bank' => 'BRI'],
['name' => 'John', 'amount' => 1000, 'type' => 2, 'bank' => 'BRI'],
['name' => 'John', 'amount' => 2000, 'type' => 2, 'bank' => 'BRI'],
['name' => 'Jane', 'amount' => 500, 'type' => 1, 'bank' => 'BRI'],
['name' => 'Jane', 'amount' => 500, 'type' => 1, 'bank' => 'BRI'],
['name' => 'Smith', 'amount' => 500, 'type' => 1, 'bank' => 'BNI'],
['name' => 'Smith', 'amount' => 1000, 'type' => 2, 'bank' => 'BNI'],
];
$group = [];
foreach ($array as $item) {
$key = $item['name'].'-'.$item['bank'].'-'.$item['type'];
if (isset($group[$key])) {
$group[$key]['data'][] = $item;
} else {
$group[$key] = [
'key' => $key,
'parentKey' => $item['bank'].'-'.$item['type'],
'data' => [$item],
'group' => []
];
}
}
var_dump($group);
var_dump('------------');
foreach ($group as $groupKey => $g) {
foreach ($g['data'] as $dataKey => $d) {
$group[$groupKey]['group'][$d['amount']][] = $d;
}
unset($group[$groupKey]['data']); // For clean result
$group[$groupKey]['group'] = array_values($group[$groupKey]['group']);
}
var_dump($group);
var_dump('------------');
$finalGroup = [];
foreach ($group as $g) {
foreach ($g['group'] as $groupKey => $items) {
$groupKey = $g['parentKey'].'-'.$groupKey;
foreach ($items as $item) {
$finalGroup[$groupKey][] = $item;
}
}
}
$finalGroup = array_values($finalGroup);
var_dump($finalGroup);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment