16

I have an array in PHP that looks like this:

  [0]=>
       array(2) {
           ["name"]=>
              string(9) "My_item"
           ["url"]=>
              string(24) "http://www.my-url.com/"
       }
  [1]=>
     array(2) {
         ["name"]=>
             string(9) "My_item"
         ["url"]=>
            string(24) "http://www.my-url2.com/"
     }

The two values in "name" are the same in this two items. I want to sort out duplicates like this.

How do I create an unique array by checking the "name" value?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • [how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php](http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – Sascha Galley Jun 21 '11 at 08:45
  • 2
    What array do you want to end up with? Given the two values for URL are different, does one of them have to go? If so, how would you determine which to lose? – Pavling Jun 21 '11 at 08:46
  • 1
    http://stackoverflow.com/questions/6417352/php-de-duplicate-keys-in-different-objects-in-array About objects, but beside this exactly the same – KingCrunch Jun 21 '11 at 08:47
  • Can you show the result you expect? – Karolis Jun 21 '11 at 08:51
  • Have a look at the [PHP-ARRAY-UNIQUE](http://php.net/manual/en/function.array-unique.php) function. – Sujit Agarwal Jun 21 '11 at 08:48

6 Answers6

34

basically

$unique_array = [];
foreach($your_array as $element) {
    $hash = $element[field-that-should-be-unique];
    $unique_array[$hash] = $element;
}
$result = array_values($unique_array);
TeNNoX
  • 1,899
  • 3
  • 16
  • 27
user187291
  • 53,363
  • 19
  • 95
  • 127
21

Serialisation is very useful for simplifying the process of establishing the uniqueness of a hierarchical array. Use this one liner to retrieve an array containing only unique elements.

$unique = array_map("unserialize", array_unique(array_map("serialize", $input)));
GordyD
  • 5,063
  • 25
  • 29
2

Please find this link useful, uses md5 hash to examine the duplicates:

http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html

Quick Glimpse:

/**
 * Create Unique Arrays using an md5 hash
 *
 * @param array $array
 * @return array
 */
function arrayUnique($array, $preserveKeys = false)
{
    // Unique Array for return
    $arrayRewrite = array();
    // Array with the md5 hashes
    $arrayHashes = array();
    foreach($array as $key => $item) {
        // Serialize the current element and create a md5 hash
        $hash = md5(serialize($item));
        // If the md5 didn't come up yet, add the element to
        // to arrayRewrite, otherwise drop it
        if (!isset($arrayHashes[$hash])) {
            // Save the current element hash
            $arrayHashes[$hash] = $hash;
            // Add element to the unique Array
            if ($preserveKeys) {
                $arrayRewrite[$key] = $item;
            } else {
                $arrayRewrite[] = $item;
            }
        }
    }
    return $arrayRewrite;
}

$uniqueArray = arrayUnique($array);
var_dump($uniqueArray);

See the working example here: http://codepad.org/9nCJwsvg

Rakesh Sankar
  • 9,337
  • 4
  • 41
  • 66
  • @Symcbean This works even if the value in the 2nd level are unique, not just first value. Why this doesnot address the question? It gives you the output, please see the working example. – Rakesh Sankar Jun 21 '11 at 11:59
0

Simple Solution:

/**
 * @param $array
 * @param null $key
 * @return array
 */
public static function unique($array,$key = null){
    if(null === $key){
        return array_unique($array);
    }
    $keys=[];
    $ret = [];
    foreach($array as $elem){
        $arrayKey = (is_array($elem))?$elem[$key]:$elem->$key;
        if(in_array($arrayKey,$keys)){
            continue;
        }
        $ret[] = $elem;
        array_push($keys,$arrayKey);
    }
    return $ret;
}
0
function unique_multidim_array($array, $key) { 
            $temp_array = array(); 
            $i = 0; 
            $key_array = array(); 

            foreach($array as $val) { 
                if (!in_array($val[$key], $key_array)) { 
                    $key_array[$i] = $val[$key]; 
                    $temp_array[$i] = $val; 
                } 
                $i++; 
            } 
            return $temp_array; 
        } 
$result = unique_multidim_array($visitors,'ip');
-5

Given that the keys on the array (0,1) do not seem to be significant a simple solution would be to use the value of the element referenced by 'name' as the key for the outer array:

["My_item"]=>
   array(2) {
       ["name"]=>
          string(9) "My_item"
       ["url"]=>
          string(24) "http://www.my-url.com/"
   }

...and if there is only one value other than the 'name' why bother with a nested array at all?

["My_item"]=>"http://www.my-url.com/"
symcbean
  • 47,736
  • 6
  • 59
  • 94