首页 > 解决方案 > 在while循环的每次迭代中添加一个计数到动态数组键

问题描述

嗨,我正在制作一个轮询功能。在下面的代码中,我试图通过将数组 $count 的键存储为答案的id+=来计算它被选为答案的次数来计算答案的数量。

我遇到的问题是$count[$option_id] += 1; 不起作用。不知道我在逻辑上做错了什么。在数据库中存在记录,我可以确认查询运行良好并获得结果。

每票可能有 2 个答案。例如:让我们用 ID 1 和 2 回答。所以,最后,它应该输出类似

details: {1: 20, 2: 50}

这意味着有 20 人为答案 1 投票,而 50 人为答案 2 投票。

任何帮助都会很棒,谢谢

$answer_count = 0;
$count = array();

$query = "SELECT * FROM `votes` where ques_id = 55";
$stmt = $this->db_obj->query_exec($query);

while($info = mysqli_fetch_array($stmt)){
    $answer_count++;
    $option_id = $info['option_id'];
    $count[$option_id] += 1;
}
return json_encode(array("success" => "1","total" => $answer_count,"details" => $count));

标签: php

解决方案


推荐阅读