如何使用array_count_values​​()和MySQL计数值发生 [英] How to use array_count_values() and mySQL to count value occurrence

查看:107
本文介绍了如何使用array_count_values​​()和MySQL计数值发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对应于被评为上的图像列的MySQL数据库表。值被001.JPG - 013.jpg。我需要弄清楚有多少次,每次形象已投票支持。我尝试以下code,并得到了计数002.JPG,但没有其他的图像。至少有25票,因为这一刻。这里是code我试图用

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

据我所知,array_count_values​​()是计算每票出现的方式,但所有我能找到的例子不能说明如何使用MySQL配对这一点。任何帮助将是AP preciated!

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!

推荐答案

您需要GROUP BY和COUNT():

You need GROUP BY and COUNT():

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

这将返回两列:1的图像,1票对这一形象的号码:

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
...

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

这篇关于如何使用array_count_values​​()和MySQL计数值发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆