检查状态== 1或0从无PHP循环数组 [英] Check status == 1 or 0 from an array without PHP loop
问题描述
一个字preSS插件,我使用的是简单的 WPDB $
查询,如:
For a WordPress plugin, I am using a simple $wpdb
query like:
global $wpdb;
$table = $wpdb->wp_table_name = $wpdb->prefix . "wp_table_name";
$the_query = $wpdb->get_results(
"SELECT *
FROM $table;
");
它给像数组(使用的var_dump()
)
array
0 =>
object(stdClass)[342]
public 'id' => string '1' (length=1)
public 'name' => string 'The Name' (length=8)
public 'status' => string '1' (length=1)
1 =>
object(stdClass)[341]
public 'id' => string '2' (length=1)
public 'name' => string 'The Name 2' (length=10)
public 'status' => string '0' (length=1)
在视图列表我想说明一个简单的计数器,如:
On the view list I want to show a simple counter like:
Total: 2; Active: 1; Inactive: 1
有关总,我用一个简单的计数()
:
For the total, I used a simple count()
:
<?php echo count($the_query); ?>
它的正常工作。现在,我想说明的另外两个数字,但[如果可能的话] 无任何环路
我想使用多个循环可以在页面放缓。我搜索了很多,他们所提出的建议 in_array()
或 array_key_exists()
。但他们似乎搜索索引,他们不能检查它是否是 ==
1或0。
I guess using many loops can slow down the page. I searched many, they are suggesting in_array()
or array_key_exists()
. But they seems search for the index, they can't check whether it's ==
1 or 0.
推荐答案
与其他反应达成一致,循环是不是天生坏。在这种情况下,一个循环可能是让你以后最简单的方法。
Agreeing with the other responses, loops aren't inherently bad. In this case, a loop is probably the simplest way to get what you're after.
有方法通过使用更实用的风格,例如使用array_reduce避免环路。例如:
There are ways to avoid the loop by using a more functional style, such as using array_reduce. eg.
$active = array_reduce($the_query, function ($result, $item) {
if ($item->status === '1') {
return $result + 1;
}
return $result;
});
var_dump($active);
不过,这仍是要执行一个循环的抽象化了到底层的C实现。
Though, this is still going to perform a loop it's abstracted away into the underlying C implementation.
这是否是一个性能改进还是不行,我不能肯定(我不怀疑)。你必须分析您的code。它主要是风格上的选择。
Whether this is a performance improvement or not, I'm not certain (I suspect not). You'd have to profile your code. It's mostly a stylistic choice.
下面是例子工作的codePAD:的http:// codepad.viper-7.com/JFzUga
Here is a codepad of the example working: http://codepad.viper-7.com/JFzUga
这篇关于检查状态== 1或0从无PHP循环数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!