我正在尝试计算每个值出现在mysql数据库的列中的次数,然后将其输出。
我的代码:
require("db_connection.php");
$sql = "SELECT name, q1_MC, q2, q3, q4, q5, q6, q7, q8_MC FROM commenttable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["name"]. "</td><td>" . $row["q1_MC"] . "</td><td>" . $row["q2"] . "</td><td>" . $row["q3"] . "</td><td>" . $row["q4"] . "</td><td>" . $row["q5"] . "</td><td>" . $row["q6"] . "</td><td>" . $row["q7"] . "</td><td>" . $row["q8_MC"] . "</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
因此q1_MC和q2_MC是我要计算其字段频率的列。他们采用1-5的数字。
我一直在尝试将以下数组合并到我的代码中,但是我不知道如何。
$a=array("1","2","3","4","5");
print_r(array_count_values($a));
[您可以使用sql来获得您需要的SQL结果,您可以使用q1_MC和q2_MC来区分和分组
SELECT name, count(distinct q1_MC) freq1 , count(distinct q2_MC) freq2
FROM commenttable
GROUP BY name
在读取所有数据时可能最容易对它们进行计数...
$counts = array('q1_MC' => array(0, 0, 0, 0, 0), 'q2_MC' => array(0, 0, 0, 0, 0));
while($row = $result->fetch_assoc()) {
$counts['q1_MC'][$row['q1_MC']]++;
$counts['q2_MC'][$row['q2_MC']]++;
// ...
}
print_r($counts);