By looking at your data, it appears that you could filter through your array of objects by comparing the uniqueness of ONE property. If that's the case, when dealing with very large arrays, it's much more efficient to compare a single property instead of essentially turning each object into a string and doing a comparison that way.
Here's a function that should return objects that are unique by one property:
function returnUniqueProperty($array,$property) {
$tempArray = array_unique(array_column($array, $property));
$moreUniqueArray = array_values(array_intersect_key($array, $tempArray));
return $moreUniqueArray;
}
$uniqueObjectsById = returnUniqueProperty($yourArray, 'category_id');
Explanation:
- We pass in to our function, the array, and the property name of column you want to perform the "uniqueness" comparison with.
- Then we use php's
array_column()
function to return an array of only the property we want to compare. This array will have the same index values as our original array. php.net
- Then we use
array_unique()
to filter out any duplicates in our temporary array. Crucially, by default, this will remove duplicates, but preserve the original index positions of each unique property value. php.net
- Now, we just have to match the index positions of our unique array of property values with our original array's index values, with
array_intersect_key()
. php.net
- Finally, we want to "compact" our array, so we
array_values()
, which returns a new array with a fresh index in numerical order. php.net