tags:

views:

146

answers:

3

Possible Duplicate:
php multi-dimensional array remove duplicate

I have an array like this:

$a = array ( 
    0 => array ( 'value' => 'America', ), 
    1 => array ( 'value' => 'England', ),  
    2 => array ( 'value' => 'Australia', ), 
    3 => array ( 'value' => 'America', ), 
    4 => array ( 'value' => 'England', ), 
    5 => array ( 'value' => 'Canada', ), 
)

How can I remove the duplicate values so that I get this:

$a = array ( 
    0 => array ( 'value' => 'America', ), 
    1 => array ( 'value' => 'England', ),  
    2 => array ( 'value' => 'Australia', ), 
    4 => array ( 'value' => 'Canada', ), 
)

I tried using array_unique, but that doesn't work due to this array being multidimensional, I think.

Edit: I also need this array to be multi-dimensional and in this format, I can't flatten it.

Thanks.

Thanks!

+1  A: 

Use SORT_REGULAR flag.

$unique_array = array_unique($a, SORT_REGULAR);

I'm not sure why it helps but it does. At least with php 5.3

Sejanus
From the php docs: **`Note:`** `Note that array_unique() is not intended to work on multi dimensional arrays.`
Andy E
Oh, I'm on 5.2, it's not working for me.
Mark
Well probably you will need to write your own function in that case.
Sejanus
works here as well (5.2.11 and 5.3)
stereofrog
+3  A: 

Here :)

<?php
 $a = array ( 
    0 => array ( 'value' => 'America', ), 
    1 => array ( 'value' => 'England', ),  
    2 => array ( 'value' => 'Australia', ), 
    3 => array ( 'value' => 'America', ), 
    4 => array ( 'value' => 'England', ), 
    5 => array ( 'value' => 'Canada', ), 
);

$tmp = array ();

foreach ($a as $row) 
    if (!in_array($row,$tmp)) array_push($tmp,$row);

print_r ($tmp);
?>
Marcx
According to [php.net](http://php.net/array_push), it's better to use `$tmp[] = $row` instead of `array_push($tmp, $row)`. Otherwise: nice answer.
middus
ah lol, you'r right, but now I'm a doubt about, why should I use array_push? :D ahah
Marcx
+3  A: 

array_unique is using string conversion before comparing the values to find the unique values:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

But an array will always convert to Array:

var_dump("Array" === (string) array());

You can solve this by specifying the SORT_REGULAR mode in the second parameter of array_unique:

$unique = array_unique($a, SORT_REGULAR);

Or, if that doesn’t work, by serializing the arrays before and unserializing it after calling array_unique to find the unique values:

$unique = array_map('unserialize', array_unique(array_map('serialize', $a)));
Gumbo
Great solution as well. thanks.
Mark
That's why you need SORT_REGULAR flag, to keep arrays from conversion to strings. In theory, at least.
Sejanus
@Sejanus: That’s what I thought too. But it seems that it doesn’t work for Mark. So I proposed an alternative solution.
Gumbo