How to check if JSON object is empty in PHP?

后端 未结 5 2126
别那么骄傲
别那么骄傲 2020-12-15 04:57

I\'m reading JSON data with PHP and that data contains empty objects (like {}). So the problem is, I have to handle the case when object is empty in different m

5条回答
  •  再見小時候
    2020-12-15 05:38

    I had to tell if an object was empty or not, but I also had to ignore private and protected properties, so I made this little function with which you can do this.

    function empty_obj(&$object, $ignore_private = true, $ignore_protected = true) {
      $obj_name = get_class($object);
      $obj = (array)$object;
    
      foreach(array_keys($obj) as $prop) {
        $is_private = $is_protected = false;
    
        $prop = preg_replace("/[^\w*]/", '', $prop);
        $prop_name = str_replace(array($obj_name, '*'), '', $prop);
    
        if(preg_match("~^$obj_name$prop_name$~", $prop))
          $is_private = true;
        if(preg_match("~^\*$prop_name$~", $prop))
          $is_protected = true;
    
        if(!$is_private || !$is_protected || ($is_private && !$ignore_private) || ($is_protected && !$ignore_protected))
          return;
      }
      return true;
    }
    

提交回复
热议问题