简体   繁体   中英

How to use array_count_values() and mySQL to count value occurrence

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:

<?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!

You need GROUP BY and 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:

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>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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