开发者

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..


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);


You can actually do it using an SQL query. For example, we have this table:

create table lol (id_deseada int);
insert into lol values (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);

You can select the id_deseada's from the database sorting by repetitions by using grouping and ordering.

SELECT id_deseada FROM lol
GROUP BY id_deseada
ORDER BY COUNT(*) DESC

Result: 1, 5, 9, 2, 3, 4.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜