1

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?

1
  • 2
    You shouldn't be using mysql extension, but mysqli instead. mysql is deprecated by PHP. Commented Jul 31, 2014 at 17:00

4 Answers 4

2
$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

Sign up to request clarification or add additional context in comments.

1 Comment

Simple and effective :)
2

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;  
}

1 Comment

@Cheruvian: I can not use "WHERE status = 1" because I need other values in the result where status != 1
0

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;

1 Comment

This will replicate the count to every row though. Generally frowned upon in DB queries
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.