Select only unique array values from this array

若如初见. 提交于 2020-01-09 10:07:30

问题


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


回答1:


$uniques = array();
foreach ($array as $obj) {
    $uniques[$obj->product_sku] = $obj;
}

var_dump($uniques);



回答2:


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);



回答3:


The default behavior of function array_unique() is to treat the values inside as strings first. So what's happening is that PHP is attempting to turn your objects into strings (which is throwing the error).

You can modify your function call like this:

$uniqueArray = array_unique($rows, SORT_REGULAR);

This will compare values without changing their data type.




回答4:


Please check below code, I hope this will be helpful to you.

$resultArray = uniqueAssocArray($actualArray, 'product_sku');

function uniqueAssocArray($array, $uniqueKey) 
{
   if (!is_array($array)) 
   {
     return array();
   }
   $uniqueKeys = array();
   foreach ($array as $key => $item) 
   {
     $groupBy=$item[$uniqueKey];
     if (isset( $uniqueKeys[$groupBy]))
     {
        //compare $item with $uniqueKeys[$groupBy] and decide if you 
        //want to use the new item
        $replace= false; 
     }
    else
    {
        $replace=true;
    }
    if ($replace) 
      $uniqueKeys[$groupBy] = $item;   
 }
 return $uniqueKeys;
}


来源:https://stackoverflow.com/questions/11340450/select-only-unique-array-values-from-this-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!