I have an array of objects generated from server side which I want to filter for duplicates in PHP ...
Below is the generated array
array:5 [▼
0 => {#204 ▼
+"category_name": "Fashion"
+"category_id": "fashion"
}
1 => {#205 ▼
+"category_name": "Fashion"
+"category_id": "fashion"
}
2 => {#209 ▼
+"category_name": "Shirts"
+"category_id": "shirts"
}
3 => {#210 ▼
+"category_name": "Health"
+"category_id": "health"
}
4 => {#211 ▼
+"category_name": "Shirts"
+"category_id": "shirts"
}
]
Here Array 0 and 1, Array 2 and Array 4 have same values, how to filter and get only a single values for the duplicate in the existing array or a newly generated array.
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:
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.netarray_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.netarray_intersect_key(). php.netarray_values(), which returns a new array with a fresh index in numerical order. php.netUse array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With