我检查过类似的问题,但它对我的精确问题没有帮助。
所以,我的 table 是这样的:
id age
1 30
2 36
3 30
4 52
5 52
6 30
7 36
等..
我需要计算年龄的频率:
age freq
30 2
36 3
52 2
我怎样才能捕获这个频率? 在此之后我将需要处理这些数据,所以可能需要使用数组? 谢谢!
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'age');
data.addColumn('number', 'freq');
<?php
while($row = mysql_fetch_row($result))
{
$frequencies[$row[0]] = $frequencies[1];
echo "data.addRow(['{$row[0]}', {$row[1]}]);";
}
?>
目标是建立图表
最佳答案
您需要按共同年龄对行进行分组,然后计算每组中有多少人:
SELECT age, COUNT(*) AS freq FROM ages GROUP BY age
然后要将其转换为数组,请在 PHP 中执行此操作:
$frequencies = array ();
$result = mysql_query('SELECT age, COUNT(*) AS freq FROM table GROUP BY age');
if($result === false) { handle error here... }
while($row = mysql_fetch_row($result)) {
$frequencies[$row[0]] = $row[1];
}
您现在有一个名为 $frequencies 的关联数组,其中年龄作为键,频率作为值。
关于Mysql 计数频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13398116/