1

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 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.