1

我需要从数组中找到最常见的值(不是 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 个数字数组。

4

1 回答 1

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)
于 2013-09-26T13:35:43.707 回答