如何使用array_count_values()和mySQL计数值发生

时间:2021-12-09 21:37:07

I have a mySQL database table with a column that corresponds to an image that has been voted on. The values are 001.jpg - 013.jpg. I need to figure out how many times each image has been voted for. I tried the following code, and got a count for 002.jpg, but none of the other images. There are at least 25 votes as of this moment. Here is the code I tried to use:

我有一个mySQL数据库表,其中的列对应于已投票的映像。数值为001.jpg - 013.jpg。我需要算出每张图片被投了多少次票。我尝试了下面的代码,得到了一个002.jpg的计数,但是没有其他的图像。目前至少有25票。下面是我尝试使用的代码:

<?php
$db = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("club",$db);
$q = mysql_query("SELECT image FROM january");
$array = mysql_fetch_array($q);
$results = array_count_values($array);
         for each
         while (list ($key,$val) = each($results)) {
         echo "$key -> $val <br>";
         }
?>

I understand that array_count_values() is the way to count the occurrence of each vote, but all the examples I can find don't show how to pair this with mySQL. Any help would be appreciated!

我理解array_count_values()是计算每次投票出现次数的方法,但是我能找到的所有示例都没有说明如何将其与mySQL进行匹配。如有任何帮助,我们将不胜感激!

1 个解决方案

#1


3  

You need GROUP BY and COUNT():

您需要GROUP BY和COUNT():

SELECT image, COUNT(*) as votes FROM january GROUP BY image

This will return two columns: 1 for the image, and 1 for the number of votes for this image:

这将返回两列:1为图像,1为图像的投票数:

image     votes
001.jpg   1
002.jpg   32
...

Full code:

完整的代码:

$db = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("club",$db);
$q = mysql_query("SELECT image, COUNT(*) as votes FROM january GROUP BY image");

$votes = array();
while ($row = mysql_fetch_assoc($q)) {
    $votes[$row['image']] = $row['votes'];
}

// $votes is an array of 'image' => 'votes'

foreach($votes as $image => $count) {
    echo "$image: $count<br>";
}

#1


3  

You need GROUP BY and COUNT():

您需要GROUP BY和COUNT():

SELECT image, COUNT(*) as votes FROM january GROUP BY image

This will return two columns: 1 for the image, and 1 for the number of votes for this image:

这将返回两列:1为图像,1为图像的投票数:

image     votes
001.jpg   1
002.jpg   32
...

Full code:

完整的代码:

$db = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("club",$db);
$q = mysql_query("SELECT image, COUNT(*) as votes FROM january GROUP BY image");

$votes = array();
while ($row = mysql_fetch_assoc($q)) {
    $votes[$row['image']] = $row['votes'];
}

// $votes is an array of 'image' => 'votes'

foreach($votes as $image => $count) {
    echo "$image: $count<br>";
}