简体   繁体   中英

php “count()” function and DB

I have a Joomla 1.5 site. I have articles in my site with different "status". What I'm trying to do is "count" and show how many articles have for example "status = 1"(expired) or "status = 3"(blocked) or "status = 2"(active) etc..

Here is the statuses in PhpMyAdmin - http://awesomescreenshot.com/07a8ijz75

Here is what I wrote, but it ALWAYS gives me same result - 1

<?php echo count($this->row->status==1) ?>

Did I miss something? Thanks

Use the SQL count function.

select count(*) from articles where status = 1;

Use your DB! If you are sorting, counting, etc, data from a database in PHP code you're doing it wrong .

If you want all statuses, do something like:

select status, count(*) from articles group by status;

The count function in PHP counts all the elements in an array, and in your example you passed it a boolean value. As a result count doesn't know what to do with it, and so it returns -1, which isn't a valid count.

My PHP is really rusty (I haven't used it in a looong time), but here are two possible ways to accomplish what you want:

1. Use a function map/reduce style

<?php
$row[0]->status = 1;
$row[1]->status = 2;
$row[2]->status = 1;
$row[3]->status = 3;
$row[4]->status = 1;

// Count the number of statuses that are equal to 1
echo array_reduce(array_map(function($x) {
    return $x->status == 1 ? 1: 0;
}, $row), function($x, $y) {return $x + $y;});

You'll have to replace the $row variable with $this->row, obviously. The code is essentially working in two steps. The inner part:

array_map(function($x) {
    return $x->status == 1 ? 1: 0;
}, $row)

Creates a list where every status that's equal to 1 becomes a 1 and everything else becomes a 0. So you have an array of "array(1, 0, 1, 0, 1)". The out part of the code:

array_reduce( ... , function($x, $y) {return $x + $y;});

Takes the new array as the first argument and sums it all up by passing in the first two values of the array into the function, and then each following value and the result of the last function call. As a result all the values get summed, and you have a proper count of the matching values.

2. Use a simple procedural style

<?php
$row[0]->status = 1;
$row[1]->status = 2;
$row[2]->status = 1;
$row[3]->status = 3;
$row[4]->status = 1;

// Do it again, but in a procedural style
$num_1_statuses = 0;
foreach ($row as $r) {
    if ($r->status == 1) {
        $num_1_statuses++;
    }
}
echo $num_1_statuses;

This should be really straightforward, it just has a variable that gets incremented whenever a row's status matches.

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