How to use "count if" in PHP

4

I need to make a count se in PHP . I have a table with several statuses, and I want to count only one type. I need to count by PHP. By SQL is impracticable.

$data = Connection::Select('SELECT * FROM tabela');

$row = $data->fetchAll();

echo count($row->status === 1);

echo count($row->status === 2);

echo count($row->status === 3);

What is it like?

    
asked by anonymous 27.01.2017 / 18:54

1 answer

12

If you REALLY want to rely on PHP you'll need something like this:

$row = $data->fetchAll();

$i = 0;
foreach($row as $item) {
    if( $item['status'] === 1 ) ++$i;
    //  ^^^^^^^^^^^^^^^^^^^^^ aqui vai a condição desejada
}

echo $i; // $i tem o resultado total da contagem

In SQL you can do this if you want to return everything but count a special condition:

SELECT *, SUM( IF( campo atende condicao ), 1, 0 ) AS contados FROM tabela

In this way, everything is returned, but SUM will add 1 to those that serve, 0 to those that do not serve, playing the role of% conditional%.

Note that because of the volume of data, it may not make up for the COUNT to return the sum on all lines, you must choose the best solution as the case may be.

If you want to count separately, that's it:

SELECT COUNT(*) AS contados FROM tabela WHERE status = condicao desejada
    
27.01.2017 / 18:59