Select only unique array values from this array

RhymeGuy picture RhymeGuy · Jul 5, 2012 · Viewed 37.3k times · Source

I have the following variable $rows:

Array (

[0] => stdClass Object
    (
        [product_sku] => PCH20
    )

[1] => stdClass Object
    (
        [product_sku] => PCH20
    )

[2] => stdClass Object
    (
        [product_sku] => PCH19
    )

[3] => stdClass Object
    (
        [product_sku] => PCH19
    )

)

I need to create second array $second containing only unique values:

Array (

[0] => stdClass Object
    (
        [product_sku] => PCH20
    )

[1] => stdClass Object
    (
        [product_sku] => PCH19
    )

)

But when i run array_unique on $rows, i receive:

Catchable fatal error: Object of class stdClass could not be converted to string on line 191

Answer

KingCrunch picture KingCrunch · Jul 5, 2012

array_unique()

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.

Also note the changenotes below

5.2.10 Changed the default value of sort_flags back to SORT_STRING.

5.2.9 Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.

$values = array_unique($values, SORT_REGULAR);