【问题标题】:Group Collection by multiple column - Laravel按多列分组集合 - Laravel
【发布时间】:2019-06-28 13:05:08
【问题描述】:

所以,我在 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,每个 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 分组,它不能解决我的问题

非常感谢

【问题讨论】:

    标签: php arrays laravel collections


    【解决方案1】:

    这也有效!

       $results = $collection->groupBy('OC')->map(function($array){
    
            $result = [];
    
            foreach($array[0] as $key => $arr){
              $result += [$key => $array->max($key)];
            }
            return $result;
    
        })->values();
    

    【讨论】:

      【解决方案2】:

      您可以使用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 var.

      【讨论】:

      • 谢谢,就像一个魅力,只需要删除 ' ,[]) ->values(); ' 可能是由于 laravel 版本,但它的工作原理
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 2017-02-01
      • 2014-06-04
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      相关资源
      最近更新 更多