所以,我在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"}
];
我需要分组,所以我有一个类型的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"},
];
最有效的方法是什么?有人可以告诉我,我尝试使用-> groupBy,但是我只能按OC分组,这不能解决我的问题
非常感谢
答案 0 :(得分:0)
您可以使用reduce
功能...类似:(未测试)
如果您的数据是集合:
$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();
或者如果您的数据是数组:
$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;
}, []));
然后,您将值保存在$modified
变量中。
答案 1 :(得分:0)
这工作呢!
$results = $collection->groupBy('OC')->map(function($array){
$result = [];
foreach($array[0] as $key => $arr){
$result += [$key => $array->max($key)];
}
return $result;
})->values();