markuszeller

Calc percentage of keys

Aug 3rd, 2020 (edited)
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.62 KB | None | 0 0
  1. // You can count how many occurences are there, and then calculate the percentage of each.
  2.  
  3. $statusArr = [
  4.     'On Track',
  5.     'Not Started',
  6.     'On Track',
  7.     'Stuck',
  8.     'Completed',
  9.     'Stuck',
  10.     'On Track',
  11.     'Completed'
  12. ];
  13.  
  14. $percentages = [];
  15. foreach($statusArr as $value) {
  16.     $percentages[$value] = isset($percentages[$value]) ? ++$percentages[$value] : 1;
  17. }
  18.  
  19. $scalar = 100 / count($statusArr);
  20. foreach ($percentages as $key => $count) {
  21.     $percentages[$key] = $scalar * $count;
  22. }
  23.  
  24. print_r($percentages);
  25.  
  26. /*
  27. [On Track] => 37.5
  28. [Not Started] => 12.5
  29. [Stuck] => 25
  30. [Completed] => 25
  31. */
Add Comment
Please, Sign In to add comment