Skip to content
Advertisement

Get occurences of an object in an object array PHP

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"
}]

Advertisement

Answer

You don’t need to use any elaborate serialization or encoding to create composite keys for grouping. Just implode each row’s values (assuming they all contain the same columns in the same order) to create an identifying key for the result array.

On the first encounter, store the row’s data in the group and set the group’s count to 1; on any subsequent encounter, increment the group’s counter.

Code: (Demo)

$result = [];
foreach ($array as $row) {
    $compositeKey = implode('_', $row);
    if (!isset($result[$compositeKey])) {
        $result[$compositeKey] = $row + ['count' => 1];
    } else {
        ++$result[$compositeKey]['count'];
    }
}
var_export(array_values($result));

Output:

array (
  0 => 
  array (
    'manufacturer' => 'KInd',
    'brand' => 'ABC',
    'used' => 'true',
    'count' => 2,
  ),
  1 => 
  array (
    'manufacturer' => 'KInd',
    'brand' => 'ABC',
    'used' => 'false',
    'count' => 1,
  ),
)

Other posts that leverage multiple identifying column values for grouping:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement