从对象数组中计算百分比


Calculate percentage from a array of objects

如何计算数组中有多少元素这样有一个非空的数据字段,在百分比?

[elements] => Array
        (   [abc] => Object
                (                    
                    [data] => Array ([0] => 'something')                      
                )    
            [def] => Object
                (                    
                    [data] => Array ()
                )
            ...

在这个例子中,它应该是50%,因为有2个元素,其中1个元素在data…

$percent = count(array_filter($elements, function($ele){return !empty($ele->data);})) / count($elements) *100;

循环的作用:

if (sizeof($elements) != 0) { // Avoids division by zero
  $count = 0;
  for ($i=0; $i<sizeof($elements); $i++) {
    if (!empty($element[$i]->data)) {
      $count++;
    }
  }
  $pcent = ($count / sizeof($elements)) * 100; // You can use round($pcent) to avoid some horrible floats
  echo $pcent;
}