简体   繁体   English

通过重复排序一个整数数组,并删除重复项

[英]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] 我需要在php中做到这一点,可以说我有[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]我想要[1,5,9,2,3,4]

but my situation its a bit different, it's result from a mysql query 但是我的情况有点不同,这是来自mysql查询的结果

i have only an asociative atribute 'id_deseada', so i do now 我只有一个关联的属性“ id_deseada”,所以我现在开始

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' ? 按重复次数排序$ result的顺序,或者在具有新字段“ 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','...) 选择id.deseada,tags。*的articles.id。从文章,标签中选择WHERE tags.id_article = article.id AND tags.name IN(“名称一”,“名称二”,“表单搜索输入”,“ ...”)

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. 您实际上可以使用SQL查询来完成。 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. 您可以使用分组和排序从数据库排序中选择id_deseada

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

Result: 1, 5, 9, 2, 3, 4. 结果:1、5、9、2、3、4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM