Sergio
Sergio

Reputation: 1239

how to count values in php array and while loop

I'm using MySQL query "SELECT * FROM ..."

And a while loop:

$rtnjsonobj = array();  
while ($k = @mysql_fetch_array($tmp)) { 
   $rtnjsonobj['status'] = $k['status'];
   $rtnjsonobj['text'] = $k['text'];
   $data[] = $rtnjsonobj;  
}

I need to count all the values in this array ​​that have status == 1. How can I do that?

Upvotes: 1

Views: 2526

Answers (4)

Vincenzo Petrucci
Vincenzo Petrucci

Reputation: 865

Use array_reduce:

array_reduce — Iteratively reduce the array to a single value using a callback function

function mycount($carry, $item) {
    $carry += $item['status'] == 1 ? 1 : 0;
    return $carry;
}

$num = array_reduce($rtnjsonobj, "mycount");

By the way you should do the count from SQL.

Upvotes: 0

Loïc
Loïc

Reputation: 11943

In your select you can imbricate another query as such :

Select *, (select count(*) from mytable where status=1) as myCounter from ...

Or increment a variable in your while loop :

$rtnjsonobj = array();
$myCounter = 0;
while ($k = @mysql_fetch_array($tmp)) { 
   $rtnjsonobj['status'] = $k['status'];
   $rtnjsonobj['text'] = $k['text'];
   $data[] = $rtnjsonobj;
   if($k['status'] == 1){$myCounter++;}
}
echo $myCounter;

Upvotes: 0

Cheruvian
Cheruvian

Reputation: 5867

No need for a loop. Please explore the SQL Language further.

Select  Count(*)
From    TableName
Where   Status = 1

Edit:

If you have your heart set on counting it in PHP, simply create a counter set to 0 and increment when the value is found.

$Count = 0;
$rtnjsonobj = array();  
while ($k = @mysql_fetch_array($tmp)) { 
   $rtnjsonobj['status'] = $k['status'];
   $rtnjsonobj['text'] = $k['text'];
   if($k['status'] == 1)
       $Count++;
   $data[] = $rtnjsonobj;  
}

Upvotes: 2

Benoit
Benoit

Reputation: 208

$counter = 0;
$rtnjsonobj = array();  
while ($k = @mysql_fetch_array($tmp)) { 
$rtnjsonobj['status'] = $k['status'];
$rtnjsonobj['text'] = $k['text'];
$data[] = $rtnjsonobj;  
if($k['status'] == 1)
   $counter = $counter + 1;
}

this will save a second query to the databse

Upvotes: 2

Related Questions