Search code examples
phpsortingno-duplicates

sort an $array of ints by repetition and remove repetitions


i need to do this in php lets say i have [1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,9,9,9,9,9] i would like [1,5,9,2,3,4]

but my situation its a bit different, it's result from a mysql query

i have only an asociative atribute 'id_deseada', so i do now

while($row = mysql_fetch_array($result){
         $t = $row['id_deseada'];
 }

so instead of that, i guess i'd have to do domething like the first example; sort $result ordered by times of repetition and maybe beetter in a new array with a new field 'count' ?

This all begins because of this query:

SELECT articles.id as id_deseada,tags.* FROM articles,tags WHERE tags.id_article = articles.id AND tags.name IN ('name one','name two','form search inputs','...)

the problem is that returns one result for every tag and i want on result for every article..


Solution

  • First, generate the value array like this:

    $vals = array();
    while($row = mysql_fetch_array($result){
             $vals[] = $row['id_deseada'];
    }
    

    Then, count and sort:

    $valCounts = array_count_values($vals);
    arsort($valCounts);
    $result = array_keys($valCounts);