Home > Software design >  Get occurences of an object in an object array PHP
Get occurences of an object in an object array PHP

Time:11-06

I have a large array with several objects, where there are several duplicates for them. I got an unique array using array_unique(PHP). Now, I need to know how to get how manny times each object was there in the original array?

I have tried array_search, and loops but nothing got the correct results. Some what similar array like here, but it's very large set, aroud 500K entries.

 [{
    "manufacturer": "KInd",
    "brand": "ABC",
    "used": "true"
},
{
    "manufacturer": "KInd",
    "brand": "ABC",
    "used": "true"
},
{
    "manufacturer": "KInd",
    "brand": "ABC",
    "used": "false"
}]

CodePudding user response:

If I understand you correctly, this should help

function getUniqWithCounts(array $data): array
{
    $result = [];
    foreach ($data as $item) {
        $hash = md5(serialize($item));

        if (isset($result[$hash])) {
            $result[$hash]['count']  ;
            continue;
        }
        $item['count'] = 1;
        $result[$hash] = $item;
    }

    return array_values($result);
}
  • Related