Search code examples
phparraysarray-unique

PHP array_unique do not work for my array


i have a function that return an array like this:

Array
(
[0] => Array
    (
        [0] => #fff4f4;
        [1] => fff4f4
    )

[1] => Array
    (
        [0] => #ffffea;
        [1] => ffffea
    )

[2] => Array
    (
        [0] => #ffc;
        [1] => ffc
    )

[3] => Array
    (
        [0] => #ccc;
        [1] => ccc
    )

[4] => Array
    (
        [0] => #eee;
        [1] => eee
    )

[5] => Array
    (
        [0] => #fffff0;
        [1] => fffff0
    )

[6] => Array
    (
        [0] => #ffd;
        [1] => ffd
    )

[7] => Array
    (
        [0] => #ddd;
        [1] => ddd
    )

[8] => Array
    (
        [0] => #ccc;
        [1] => ccc
 [...]

i need to have an array like this but only with unique values. i have tried with:

$result = array_unique($rescss);

bur unique entire array in a row, then i have tried

$result = array_unique($rescss[]);

but doesn't work.

how can i have my new array like that but with uniques values only

thanks in advance


Solution

  • Just loop the array and use a hash array to flag the value already exists, like this:

    $unique = array ();
    
    $hash = array ();
    
    foreach ( $rescss as $ele )
    {
        //seemed $ele [0] could be the primary key
        $eleKey = $ele [0];
    
        if (isset ( $hash [$eleKey] ))
            continue;
    
        $unique [] = $ele;
    
        $hash [$eleKey] = 1;
    }