【问题标题】:Proper way for count empty variables计算空变量的正确方法
【发布时间】:2009-09-14 23:40:31
【问题描述】:

我使用 kohana,当您尝试从数据库中获取数据时,它会返回类变量(如 $user->firstname)作为数据库数据。用户表有 12 列,我获取 8 列,但此时某些列可能为空(如 $user->phone)。我怎样才能找到空列号?(正确的方式..)

非常感谢

【问题讨论】:

    标签: php oop class count kohana


    【解决方案1】:

    一般来说,您可以尝试以下方法:

    /**
     * Count number of empty data members in a row object.
     */
    function countEmpty($row){
      $fields = array_keys($row->as_array());
      $cnt = 0;
      foreach($fields as $f){
        if (empty($row->$f)) $cnt++;
      }
      return $cnt;
    }
    

    【讨论】:

      【解决方案2】:

      我找到了解决方案。 PHP 有神奇的 get_object_vars 函数:

      $data = User_Model::factory()->read(
          array('id' => $user_id),
          'firstname, lastname, birthday, country, mobilephone, landphone, address'
      );
      
      $filled_data = 0;
      foreach(get_object_vars($data) as $v)
      {
          if ($v != '') $filled_data++;
      }
      return round($filled_data / count(get_object_vars($data)) * 100);
      

      【讨论】:

      • 你可以使用 count(array_filter($data->as_array()));
      猜你喜欢
      • 2016-07-11
      • 2023-03-07
      • 2019-07-16
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多