我试图计算每个值出现在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));
答案 0 :(得分:2)
您可以使用sql来获得所需的SQL结果,您可以使用sql来区分和分组,例如q1_MC和q2_MC可以使用
SELECT name, count(distinct q1_MC) freq1 , count(distinct q8_MC) freq8
FROM commenttable
GROUP BY name
答案 1 :(得分:0)
最后到达那里。我使用array_count_values php函数,然后使用foreach函数遍历数组。
$q1_MC = array();
$q8_MC = array();
if ($result->num_rows > 0) {
$counts = array('q1_MC' => array(0,0,0,0,0), 'q8_MC' => array(0,0,0,0,0));
while($row = $result->fetch_assoc()) {
array_push($q1_MC, $row['q1_MC']);
array_push($q8_MC, $row['q8_MC']);
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";
}
$q1_answers = (array_count_values($q1_MC));
$q2_answers = (array_count_values($q8_MC));
echo "<div class='row mt-5 mb-5 mr-4 ml-4'>";
echo "<table class='table' id='questionsTable'><thead><tr><th>Question 1
Multiple Choice answers</th></tr>";
foreach($q1_answers as $key => $item) {
echo "<tr><td>" . $key. "</td><td>" . $item. "</td></tr>";
}
echo "</tr></table></div>";
echo "<div class='row mt-5 mb-5 mr-4 ml-4'>";
echo "<table class='table' id='questionsTable'><thead><tr><th>Question 8
Multiple Choice answers</th></tr>";
foreach($q2_answers as $key => $item) {
echo "<tr><td>" . $key. "</td><td>" . $item. "</td></tr>";
}
echo "</tr></table></div>";