简体   繁体   中英

How to count the number of rows containing a specific number in it's column

I would like to echo a count how many rows are containing the same specific number.

I have a column called " member_group_id " in my db.

For example, the leader group id is " 4 " some members have this number assigned in the db, so I would like to do something like:

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

How could I do that?

Here is my db query:

$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");

Here's my actual loop and desired result:

while($row = mysqli_fetch_array($result)){        
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

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

You can't have an array with multiple time same key at same level, i explain :

$test['hello'] = 1;
$test['hello'] = 5;

So key hello will contains only 5 . If you want to count all keys with same value, you can write a code like this:

$array = array('1', '1', '2', 'test' => '1', '1', '2', '3', '1', '9');
$count = \count(array_keys($array, '1'));
// output of $count is 5

Search all keys corresponding to specified value, then count all keys.

If I understand, you got all the result from your query as an array, with something like pg_fetch_all :

$result = [
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 1,
    ],
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 3,
    ],
    [
        'id'     => 'whatever',
        'and'    => 'whatever',
        'other'  => 'whatever'
        'fields' => 'whatever'
        'member_group_id' => 1,
    ],
]

And you want to know how many of records have ['member_group_id'] == 1

You can use

count(
    array_filter(
        function($item) { return ($item['member_group_id'] == 1); },
        $result
    )
)

array_filter walks through the array and keeps only items for which the function returns true.

You will just need to test the $row['member_group_id'] for the value you are interested in, and then add to an accumulator if it is the right value

$countLeaders = 0;
while($row = mysqli_fetch_assoc($result)){        
    if ($row['member_group_id'] == '4') {
        $countLeaders++;
    }

    // other code if you have it
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM