removing array duplicates from associative array

189 views Asked by At

So i have:

Array (
      [animals] => Array
        (

            [0] => horse
            [1] => dog
            [2] => dog

        )
      [team] => Array
        (

            [0] => cubs
            [1] => reds
            [2] => cubs

        )
)

Trying to eliminate the repeat ones with animals and same with team.

Tried this but didn't help.

$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));

Seems like it doesn't reach deep inside, don't want either to hard code animals or team.

2

There are 2 answers

0
alu On BEST ANSWER
$data = [
    'animals' => ['horse', 'dog', 'dog'],
    'team' => ['cubs', 'reds', 'cubs']
];

$result = array_map('array_unique', $data);
print_r($result);
1
JamesG On

Here's one option:

    $ar = array( 'animals' => array( 'horse', 'dog', 'dog' ),
                 'team' => array( 'cubs', 'reds', 'cubs' ));


    foreach( $ar as &$item )
    {
        $item = array_unique( $item );
    }

    print_r( $ar );

Not as cool as using array_map(), but it works.