我需要从数组中找到最常见的值(不是0)。 我的代码:
include ("db.php");
$query = "SELECT poll1 FROM names";
$res = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
echo $row['poll1'];
}
回显结果(最小值0(默认值)和最大值3):
1
1
0
0
0
2
3
最常见的值是“1”。我不能使用array_count_values,因为有7个数组。
答案 0 :(得分:2)
这是您应该使用SQL解决的问题。
首先,您希望获得选择每个选项的人数:
SELECT poll1, COUNT(*) AS count FROM names GROUP BY poll1;
+-------+-------+
| poll1 | count |
+-------+-------+
| 0 | 3 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
+-------+-------+
4 rows in set (0.00 sec)
好的,但是您对零不感兴趣,而您只关心count
值最大的行,因此您应该按降序count
进行排序,并将其限制为1个结果:
SELECT poll1, count(*) AS count FROM names
WHERE poll1 != 0
GROUP BY poll1
ORDER BY count DESC
LIMIT 1;
+-------+-------+
| poll1 | count |
+-------+-------+
| 1 | 2 |
+-------+-------+
1 row in set (0.00 sec)