62 lines
1.3 KiB
PHP
62 lines
1.3 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Collapse a collection, by summing up fields.
|
|
*/
|
|
namespace Leenooks\Traits;
|
|
|
|
use Illuminate\Support\Collection;
|
|
|
|
trait CollectionCollapse {
|
|
/**
|
|
* Collapse a collection by summing up records according to a given key
|
|
*
|
|
* @param Collection $c Collection to collapse
|
|
* @param array $id To use as the group by key
|
|
* @param array $consolidateKeys Keys that should be summed up during the process
|
|
* @return Collection
|
|
*/
|
|
protected function collapse(Collection $c,array $id,array $consolidateKeys=[])
|
|
{
|
|
return $c->groupBy(function ($item,$key) use ($id) {
|
|
$string = '';
|
|
|
|
foreach ($id as $key) {
|
|
if ($string AND array_get($item,$key))
|
|
$string .= '.';
|
|
|
|
$string .= $item[$key];
|
|
}
|
|
|
|
return $string;
|
|
|
|
})->transform(function ($items,$key) use ($consolidateKeys) {
|
|
$newitem = [];
|
|
|
|
if ($items->count()) {
|
|
$c = 0;
|
|
|
|
foreach ($items as $item) {
|
|
if (! $c++) {
|
|
$newitem = $item;
|
|
continue;
|
|
}
|
|
|
|
foreach ($item as $k => $v) {
|
|
// Add these values to the existing ones
|
|
if (in_array($k, $consolidateKeys)) {
|
|
if (!isset($newitem[$k]))
|
|
$newitem[$k] = 0;
|
|
$newitem[$k] += $v;
|
|
}
|
|
}
|
|
}
|
|
|
|
} else {
|
|
$newitem = $items;
|
|
}
|
|
|
|
return $newitem;
|
|
});
|
|
}
|
|
} |