dongshuxi3105 2017-05-04 15:06
浏览 55
已采纳

如果数组中的任何项为空/非空,则返回boolean

I have an array of objects. I need to loop over these objects (preferably without foreach(), and if a certain key in the objects is not empty, then return true, otherwise return false.

For example,

$items = array(
    '0' => stdClass {
        name => Ryan
        suppliers => array()
    }
    '1' => stdClass {
        name => Dave
        suppliers => array(
            '0' => stdClass {}
        )
    }
)

Essentially, I need to go through the array and check the "supplier" key of the object, and if any of them are not empty, return true for the entire thing, otherwise return false.

  • 写回答

3条回答 默认 最新

  • dtczp02204 2017-05-04 15:11
    关注

    What's wrong with foreach?

    $check = function($arr) {
      foreach($arr as $o) {
         if (!empty($o->suppliers)) return true;
      }
      return false;
    };
    

    If you want to use it only in one place, use anonymous function

    I don't understand why you don't want to use foreach because thing is - foreach is only right way because you leave loop as soon as you find value

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

报告相同问题?

悬赏问题

  • ¥15 cruise如何仿真不同温度下车辆的经济性?
  • ¥20 扑克牌游戏的完整代码
  • ¥88 求帮安装Python架构的vnpy
  • ¥20 逻辑回归法分析品牌知名度和购买意向
  • ¥15 华为云主机-异常连接
  • ¥50 vue 成绩列表 输入成绩,并统计各分数段人数
  • ¥20 请教怎么绕过这个卡密系统 大家交流一下
  • ¥15 设计数字电路得到要求结果
  • ¥15 hfss 组天线阵列报错:The A and B vectors must be parallel to the XY plane,如何解决?
  • ¥30 ansible连接设备报错