合并Laravel收集结果,汇总一个字段

时间:2018-08-23 15:30:03

标签: laravel collect

我有一个结果重复的集合,但是在相关字段中有不同的数据。我想消除重复项,但通过合并该字段的值来保留其他数据。我似乎找不到一个很好的方法来做到这一点。我的结果集如下:

"bankers" => Collection {#663 ▼
  #items: array:5 [▼
    0 => Collection {#465 ▼
      #items: array:5 [▼
        "banker_id" => 13
        "banker_name" => "John Banker"
        "type" => "lending"
        "deal_score" => 1
      ]
    }
    1 => Collection {#455 ▼
      #items: array:5 [▼
        "banker_id" => 62667
        "banker_name" => "Harvey Aandreau"
        "type" => "lending"
        "deal_score" => 0
      ]
    }
    2 => Collection {#419 ▼
      #items: array:6 [▼
        "banker_id" => 13
        "banker_name" => "John Banker"
        "type" => "quotes"
        "deal_score" => 1
      ]
    }
    3 => Collection {#410 ▼
      #items: array:6 [▼
        "banker_id" => 297
        "banker_name" => "Melissa Jablonsky"
        "type" => "quotes"
        "deal_score" => 1
      ]
    }
  ]
}

我想删除第二个重复的“ John Banker”,但将“类型”字段的值添加到上一条记录,例如:

"bankers" => Collection {#663 ▼
  #items: array:5 [▼
    0 => Collection {#465 ▼
      #items: array:5 [▼
        "banker_id" => 13
        "banker_name" => "John Banker"
        "type" => "lending, quotes"
        "deal_score" => 1
      ]
    }
    1 => Collection {#455 ▼
      #items: array:5 [▼
        "banker_id" => 62667
        "banker_name" => "Harvey Aandreau"
        "type" => "lending"
        "deal_score" => 0
      ]
    }
    3 => Collection {#410 ▼
      #items: array:6 [▼
        "banker_id" => 297
        "banker_name" => "Melissa Jablonsky"
        "type" => "quotes"
        "deal_score" => 1
      ]
    }
  ]
}

我需要保留当前订单。如果需要,“类型”字段可以更改为数组。任何建议,将不胜感激。

1 个答案:

答案 0 :(得分:0)

感谢Joseph Silber提出以下建议:

$bankers->groupBy('banker_name')->map(function ($bankers) {
    return array_merge($banker[0]->all(), [
        'type' => $bankers->pluck('type')->implode(',');
    ]);
});