Select only unique array values from this array

六眼飞鱼酱① 提交于 2019-11-28 09:11:48
$uniques = array();
foreach ($array as $obj) {
    $uniques[$obj->product_sku] = $obj;
}

var_dump($uniques);

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

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.

Raju Dudhrejiya

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