How do I remove elements from an array of objects with the same name? In the case below, I want to remove elements 0 and 2 because the name is the same. I figured I could loop over every case but that seems wasteful.
array(1) {
[0]=> object(stdClass)#268 (3) {
["term_id"]=> string(3) "486"
["name"]=> string(4) "2012"
["count"]=> string(2) "40"
}
[1]=> object(stdClass)#271 (3) {
["term_id"]=> string(3) "488"
["name"]=> string(8) "One more"
["count"]=> string(2) "20"
}
[2]=> object(stdClass)#275 (3) {
["term_id"]=> string(3) "512"
["name"]=> string(8) "2012"
["count"]=> string(2) "50"
}
You can loop over the array, calculating how many times each name appears. Then you filter away those elements appearing more than once using array_filter. This will have an average runtime complexity of
O(n)(assumingO(1)for arrays), compared to the naiveO(n^2)case.Code:
For PHP versions before 5.3 you cannot use closures, so in that case, modify your code to this:
Note that this is only useful in reality for large arrays since there’s some overhead involved. It may also be hard to read if you don’t understand what’s being done. For small arrays (a few hundred elements or so) I recommend you to use the naive quadratic-time loop approach.