Search code examples
phparraysarray-unique

remove duplicates and move those that had duplicates to beginning of multi-dimensional array php


I'm creating a search function for a csv. With the result of my search I then want to remove duplicates and then move those that had duplicates to the beginning of the array.

  Array
    (
        [0] => Array
        (
            [0] => COD 21
            [1] => 4567
            [2] => Robert Wahl
        )
    [1] => Array
        (
            [0] => RT 5
            [1] => 1234
            [2] => Robert Merrill
        )
    [2] => Array
        (
            [0] => XD 62
            [1] => 1653
            [2] => Robert Hill
        )
    [3] => Array
        (
            [0] => RT 5
            [1] => 1234
            [2] => Robert Merrill
        )
)

I have a function that removes duplicates, but I'm not sure how to get it to move the values that have duplicates to the beginning of the array, and order them according to those with the most duplicates:

function arrayUnique($array) { 
    $aux_ini=array(); 
    $result=array(); 
    for($n=0;$n<count($array);$n++) 
    { 
        $aux_ini[]=serialize($array[$n]); 
    } 
    $mat=array_unique($aux_ini); 
    for($n=0;$n<count($array);$n++) 
    { 
        $result[]=unserialize($mat[$n]); 
    } 
    return $result; 
}

Any and all help is appreciated.


Solution

  • function arrayUnique($array) { 
        // count values
        $arr = array_count_values (array_map('serialize',$array)); 
        // sort in desc order
        arsort($arr);
        // take keys and restore array
        return array_map('unserialize',array_keys($arr));
    }