Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only unique array values from this array

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

like image 771
RhymeGuy Avatar asked Jul 05 '12 08:07

RhymeGuy


People also ask

What is the fastest way to find unique elements in an array?

What is the fastest way to find unique elements in an array? By using hashing There is another way to get the distinct element from the array, i.e., hashing. By using the hashing, we can get a distinct element in O(n). We traverse the array from which we want to get the distinct element.


1 Answers

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);
like image 75
KingCrunch Avatar answered Sep 17 '22 14:09

KingCrunch