如何计算列中包含特定数字的行数

我想回显一个包含相同特定数字的行数的计数。


我的数据库中有一个名为“member_group_id”的列。


例如,领导组 ID 为“4”,某些成员在 db 中分配了此编号,因此我想执行如下操作:


$countLeaders = count($row['member_group_id'] == 4);

我该怎么做?


这是我的数据库查询:


$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY 

    CASE member_group_id 

        WHEN '4' THEN 1  

        WHEN '7' THEN 2

        WHEN '8' THEN 3

        WHEN '6' THEN 4

        WHEN '11' THEN 5 

    END ASC, name ASC");

这是我的实际循环和期望的结果:


while($row = mysqli_fetch_array($result)){        

    $group = $row['member_group_id'];

    $countLeaders = count($group == 4);

}


echo "<span>" . $countLeaders . " Leaders</span>";


jeck猫
浏览 113回答 3
3回答

杨魅力

您只需要测试您感兴趣的值,然后将其添加到累加器中(如果它是正确的值)$row['member_group_id']$countLeaders = 0;while($row = mysqli_fetch_assoc($result)){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if ($row['member_group_id'] == '4') {&nbsp; &nbsp; &nbsp; &nbsp; $countLeaders++;&nbsp; &nbsp; }&nbsp; &nbsp; // other code if you have it}echo "<span>" . $countLeaders . " Leaders</span>";

慕标琳琳

如果我理解,你从你的查询中得到的所有结果都是一个数组,类似于:pg_fetch_all$result = [&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'id'&nbsp; &nbsp; &nbsp;=> 'whatever',&nbsp; &nbsp; &nbsp; &nbsp; 'and'&nbsp; &nbsp; => 'whatever',&nbsp; &nbsp; &nbsp; &nbsp; 'other'&nbsp; => 'whatever'&nbsp; &nbsp; &nbsp; &nbsp; 'fields' => 'whatever'&nbsp; &nbsp; &nbsp; &nbsp; 'member_group_id' => 1,&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'id'&nbsp; &nbsp; &nbsp;=> 'whatever',&nbsp; &nbsp; &nbsp; &nbsp; 'and'&nbsp; &nbsp; => 'whatever',&nbsp; &nbsp; &nbsp; &nbsp; 'other'&nbsp; => 'whatever'&nbsp; &nbsp; &nbsp; &nbsp; 'fields' => 'whatever'&nbsp; &nbsp; &nbsp; &nbsp; 'member_group_id' => 3,&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'id'&nbsp; &nbsp; &nbsp;=> 'whatever',&nbsp; &nbsp; &nbsp; &nbsp; 'and'&nbsp; &nbsp; => 'whatever',&nbsp; &nbsp; &nbsp; &nbsp; 'other'&nbsp; => 'whatever'&nbsp; &nbsp; &nbsp; &nbsp; 'fields' => 'whatever'&nbsp; &nbsp; &nbsp; &nbsp; 'member_group_id' => 1,&nbsp; &nbsp; ],]您想知道有多少条记录['member_group_id'] == 1您可以使用count(&nbsp; &nbsp; array_filter(&nbsp; &nbsp; &nbsp; &nbsp; function($item) { return ($item['member_group_id'] == 1); },&nbsp; &nbsp; &nbsp; &nbsp; $result&nbsp; &nbsp; ))array_filter遍历数组并仅保留函数返回 true 的项。

一只斗牛犬

你不能在同一级别有多个时间相同键的数组,我解释说:$test['hello'] = 1;$test['hello'] = 5;因此,键将仅包含 。如果要计算具有相同值的所有键,可以编写如下代码:hello5$array = array('1', '1', '2', 'test' => '1', '1', '2', '3', '1', '9');$count = \count(array_keys($array, '1'));// output of $count is 5搜索与指定值对应的所有键,然后对所有键进行计数。
打开App,查看更多内容
随时随地看视频慕课网APP