我正在举办一场比赛,为了查看结果,我编写了这段简短的代码:
date_default_timezone_set('America/New_York');
echo "Results tallied at ". date("g:i:s A")."<br /><br />";
$names = array('contestant1','contestant2','contestant3'...); //10 entries
$plots = array();
foreach ($names as $name) {
$query = $this->db->getwhere('friday', array('votedon'=>$name));//CodeIgniter Active Record
$count = $query->num_rows(); //again, CodeIgniter
echo "Votes for " . ucfirst($name).": $count <br />";
$plots[]= $count;
}
$total = $this->db->count_all('friday'); //CodeIgniter
echo "<br />Total votes: $total <br />";
$highest = 5+max($plots); //make the chart look better
$url = "http://chart.apis.google.com/chart?cht=bvg&chs=900x300&chbh=40,100,40";
$par1 = "&chds=0,$highest";
$par2 = "&chl=". implode("|",$names);
$par3 = '&chd=t:'. implode(",",$plots);
$imgsrc = $url.$par1.$par2.$par3;
echo "<img src='$imgsrc' />";
因此这会生成一个显示当前轮询结果的条形图。我想知道是否有一种优雅的方式来避免输入人们可能投票的每个独特条目。 (第 4 行 $names = ....)对于本次竞赛,“votedon”列中有 10 个可能的条目名称,但如果它是用户输入,并且我想显示/统计所有可能的结果,该怎么办?
这样的代码会是什么样子?我是编程新手,有时我自己很难想出这样的习惯用法。谢谢!
最佳答案
查询非常简单:
SELECT votedon, count(*)
FROM VOTING_TABLE
GROUP BY votedon
现在,我不知道它如何适合 codeigniter,但是来自 php 的 mysql 连接并不难,如果这确实是一个临时的事情,那么就可以了。
关于php - 如何为每个唯一的数据库条目创建一个类别? (MySQL/PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1661452/