douxian4888 2014-01-18 06:05 采纳率: 0%
浏览 55
已采纳

从没有PHP循环的数组中检查状态== 1或0

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;
    ");

It gives array like (using 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); ?>

It's working fine. Now I want to show the other two numbers, but [if possible] WITHOUT ANY LOOP.

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.

  • 写回答

5条回答 默认 最新

  • dougan1205 2014-01-18 06:24
    关注

    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.

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

    Though, this is still going to perform a loop it's abstracted away into the underlying C implementation.

    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.

    Here is a codepad of the example working: http://codepad.viper-7.com/JFzUga

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答