Group array or laravel collection with similar objects and add count

799 views Asked by At

How can I get the count of occurrence of array items while keeping the values as well. e.g.

$items = [{code: "2132", tile:"Mechanical Engineers"}, 
          {code: "2134" title: "Chemical engineers"},
          {code: :2132, title: "Mechanical Engineers}]

What I would like to achive is something like as follows:

$sortedItems = [{code: "2134" title: "Chemical engineers", count:1},
                {code: "2132" title: "Chemical engineers", count:2}]

I'm using Larave and would like to get this either by using PHP array or even Laravel collection. Whichever works better.

Appreciate your help, as I am really stuck here and not sure how to proceed.

1

There are 1 answers

0
TsaiKoga On BEST ANSWER

Use collection groupBy and map:

$items = '[{"code": "2132", "title":"Mechanical Engineers"},
             {"code": "2134", "title":"Chemical engineers"},
             {"code":"2132", "title":"Mechanical Engineers"}]';
$array = json_decode($items, true);

// try this:
$arr = collect($array)->groupBy('code')->map(function($item) {
    return array_merge($item->first(), array("count" => $item->count()));
})->all();

array_values($arr);