Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter the Unique Objects in this PHP array object [duplicate]

Tags:

arrays

php

filter

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.

like image 506
ChanX Avatar asked Feb 17 '26 14:02

ChanX


2 Answers

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:

  1. We pass in to our function, the array, and the property name of column you want to perform the "uniqueness" comparison with.
  2. 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
  3. 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
  4. 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
  5. 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
like image 174
Doomd Avatar answered Feb 19 '26 03:02

Doomd


Use array_unique() PHP function:

http://php.net/manual/en/function.array-unique.php

like image 24
Vincent Olivert Riera Avatar answered Feb 19 '26 04:02

Vincent Olivert Riera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!