【问题标题】:How to check empty object array?如何检查空对象数组?
【发布时间】:2015-10-26 09:47:41
【问题描述】:

我得到了下面一组空对象数组,当我使用 php empty 函数时,下面的对象数组绕过了 empty 函数。

stdClass Object
(
)

请建议我,如何识别空白对象数组。

【问题讨论】:

标签: php arrays object


【解决方案1】:

使用json_encode 和json_decode 将对象转换为关联数组。

$arr = json_decode(json_encode($obj), TRUE);
if (empty($arr)) {
  // Object is empty.
}

json_decode如果设置了第二个参数TRUE,则函数返回关联数组(即使传递了对象)。

工作示例:

<?php
$obj = new stdClass();
$arr = json_decode(json_encode($obj), TRUE);
if (empty($arr)) {
  echo 'empty';
}
?>

【讨论】:

    【解决方案2】:

    将其转换为数组并检查:

    $array = (array) $object;
    
    if (empty($array))
    

    或

    count($array)
    

    【讨论】:

      【解决方案3】:

      可以这样做

      $array = array_filter($array);
      if(!empty($array)) {
          echo "not empty";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多