Page 1 of 1

Help remove Multidimensional Array Duplicates

Posted: Sun Sep 20, 2009 12:37 am
by biba028
My array sample:

array[0]['id']
array[0]['name']

array[1]['id']
array[1]['name']

array[2]['id']
array[2]['name']


How can I remove the duplicates by checking the 'name' field ?

array_unique does not work, because 'id' are all different.

ANyone ?

Re: Help remove Multidimensional Array Duplicates

Posted: Sun Sep 20, 2009 1:49 pm
by ricehigh
I'm not sure if this is exactly the fastest solution, but it works :)

Code: Select all

<?php
$test[0]["id"] = 0;
$test[0]["name"] = "test";
 
$test[1]["id"] = 1;
$test[1]["name"] = "test2";
 
$test[2]["id"] = 2;
$test[2]["name"] = "test2";
 
$test[3]["id"] = 3;
$test[3]["name"] = "test2";
 
$test[4]["id"] = 4;
$test[4]["name"] = "test4";
 
$remove = array();
for($x=0;$x<count($test);$x++){
    for($y=0;$y<count($test);$y++){
        if(!in_array($y,$remove) && $x != $y && $test[$x]["name"] == $test[$y]["name"]){
            $remove[] = $x;
        }
    }
}
 
foreach($remove as $rem){
    unset($test[$rem]);
}
 
print_r($test);
?>
Output:
Array
(
    [0] => Array
        (
            [id] => 0
            [name] => test
        )
 
    [3] => Array
        (
            [id] => 2
            [name] => test2
        )
 
    [4] => Array
        (
            [id] => 2
            [name] => test4
        )
 
)

Re: Help remove Multidimensional Array Duplicates

Posted: Mon Sep 21, 2009 12:13 am
by biba028
it works.. but im thinking there must be a faster way.