Help remove Multidimensional Array Duplicates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
biba028
Forum Newbie
Posts: 2
Joined: Sun Sep 20, 2009 12:33 am

Help remove Multidimensional Array Duplicates

Post 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 ?
ricehigh
Forum Newbie
Posts: 21
Joined: Mon Sep 14, 2009 5:18 pm

Re: Help remove Multidimensional Array Duplicates

Post 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
        )
 
)
biba028
Forum Newbie
Posts: 2
Joined: Sun Sep 20, 2009 12:33 am

Re: Help remove Multidimensional Array Duplicates

Post by biba028 »

it works.. but im thinking there must be a faster way.
Post Reply