简体   繁体   中英

Calculate percentage from a array of objects

How can I calculate how many of the elements in a array like this have a non-empty data field, in percetanges?

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

            [def] => Object
                (                    
                    [data] => Array ()

                )

            ...

In this exemple it would be 50% because there are 2 elements, and 1 of them has something in data...

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

That what loops are for:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM