[英]Group Collection by multiple column - Laravel
So, i have this collection in laravel : 所以,我在laravel中有这个集合:
$collection = [
{OC: "3.01", C: "922.76", D: "0"},
{OC: "3.01", C: "0", D: "78004027.00"},
{OC: "3.02", C: "0", D: "116442.60"},
{OC: "3.03", C: "0", D: "833.83"},
{OC: "3.04", C: "772.50", D: "0"},
{OC: "3.04", C: "0", D: "3345.50"}
];
i need to group so i have one OC of a kind, each one can have one or two records (one for C != 0 and one for D != 0), in this case for example the expected result is: 我需要分组,所以我有一个类型的OC,每个可以有一个或两个记录(一个记录C!= 0,一个记录D!= 0),在这种情况下,例如,预期结果是:
$collection = [
{OC: "3.01", C: "922.76", D: "78004027.00"},
{OC: "3.02", C: "0", D: "116442.60"},
{OC: "3.03", C: "0", D: "833.83"},
{OC: "3.04", C: "772.50", "3345.50"},
];
whats the most effective way i can do it? 最有效的方法是什么? can someone please shed a light, i tried using ->groupBy but i can only group by OC and its not solving my problem 有人可以告诉我,我尝试使用-> groupBy,但是我只能按OC分组,这不能解决我的问题
much appreciated 非常感激
You can use reduce
function... something like: (Not tested) 您可以使用reduce
函数...类似:(未测试)
If your data is a collection: 如果您的数据是集合:
$modified = $collection->reduce(function ($carry, $item) {
if(empty($carry[$item->OC])){ //Not on the final array
//Create it
$carry[$item->OC] = $item;
} else { //Exists, then update C/D with maximum value
$carry[$item->OC]->C = max($carry[$item->OC]->C, $item->C);
$carry[$item->OC]->D = max($carry[$item->OC]->D, $item->D);
}
return $carry;
}, [])->values();
Or if your data is an array: 或者,如果您的数据是数组:
$modified = array_values($collection, array_reduce(function ($carry, $item) {
if(empty($carry[$item->OC])){ //Not on the final array
//Create it
$carry[$item->OC] = $item;
} else { //Exists, then update C/D with maximum value
$carry[$item->OC]->C = max($carry[$item->OC]->C, $item->C);
$carry[$item->OC]->D = max($carry[$item->OC]->D, $item->D);
}
return $carry;
}, []));
Then you have your values in $modified
var. 然后,将值保存在$modified
var中。
This works too! 这也可以!
$results = $collection->groupBy('OC')->map(function($array){
$result = [];
foreach($array[0] as $key => $arr){
$result += [$key => $array->max($key)];
}
return $result;
})->values();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.