Search code examples
phparraysunique

Unique values of the array with four fields


I've an array like this:

array(
    0 => array(1, 2, 3, 4),
    1 => array(1, 3, 2, 4),
    2 => array(1, 2, 4, 3),
    3 => array(1, 2, 5, 6)
)

I have to remove records that are repeated. So I need finally to have this array:

array(
    0 => array(1, 2, 3, 4),
    3 => array(1, 2, 5, 6)
)

The script is in PHP.

Who can help? :)


Solution

  • This should work for you:

    Just go through each sub array with array_map() and sort() the arrays. Then simply return them implode()'ed. With the created array you can just use array_unique() and then explode() the values again.

    <?php
    
        $result = array_map(function($v){
            return explode(",", $v);
        }, array_unique(array_map(function($v){
                sort($v);
                return implode(",", $v);
            }, $arr)));
    
        print_r($result);
    
    ?>
    

    output:

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
                [3] => 4
            )
    
        [3] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 5
                [3] => 6
            )
    
    )