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:
- Group/Merge rows from two 2d arrays based on 3 identifying columns and fill missing column values with null
- Group rows of data, sum number of occurrences in each group, and print data as formatted strings
- Group data in a multidimensional array based on two columns
- Group rows of a multidimensional array and form comma-separated values within each group
- Group rows by two columns, filter grouped data to only keep the lowest value, and restructure associative rows
- Group rows of data, maintain a subarray of ids within the group, and only present the lowest id in each group as the first level key
- Group multidimensional array data based on two column values and sum values of one column in each group
- how to create a pivot array in php