Yusuf Devranlı Yusuf Devranlı - 2 years ago 136
PHP Question

Getting percantages of numbers. PHP array

there is dmgs array.

$dmgs array:

Array ( [0] => 5.1k [1] => 3.8k [2] => 12.9k [3] => 10.4k [4] => 4.1k [5] => 8.0k [6] => 7.6k [7] => 14.9k [8] => 13.6k [9] => 3.0k )


0,1,2,3,4 are blue team players.
others are reds.

$blueteamdmg = $dmgs[0] + $dmgs[1] + $dmgs[2] + $dmgs[3] + $dmgs[4] ;
$redteamdmg = $dmgs[5] + $dmgs[6] + $dmgs[7] + $dmgs[8] + $dmgs[9] ;


i need to compare player's dmg to their teams dmg.

example: blue team did 15k dmg. dmgs[1] (player 2 blue team) did 7.5k dmg.
he did 50% dmg of his teams total dmg.

i need a other array that gives every players percantage of dmg.

like this:

Array (
[0] => 15% // blue team
[1] => 20% // blue team
[2] => 50% // blue team
[3] => 10% // blue team
[4] => 5% // blue team
[5] => 30% // red team
[6] => 12% // red team
[7] => 22% // red team
[8] => 28% // red team
[9] => 8% // red team )


so there will be other array named $dmgpercantages[]

but i dont know how to do this.

sorry for bad english.

$dmgpercantages = array(yuzde($dmgs[0]),yuzde($dmgs[1]),yuzde($dmgs[2]),yuzde($dmgs[3]),yuzde($dmgs[4]),yuzde($dmgs[5]),yuzde($dmgs[6]),yuzde($dmgs[7]),yuzde($dmgs[8]),yuzde($dmgs[9]));

function yuzde($dmgs[$a]) {
if ($a <= 4) {
$percentage = ($blueteamdmg / $dmgs[$a]) * 100;
echo $percentage . "%";}
else {
$percentage = ($redteamdmg / $dmgs[$a]) * 100;
echo $percentage . "%";
}
}


its not working

Answer Source

this code applying only for this particular case, assuming total players always 10:

$dmgs = array(1,2,3,4,5,6,7,8,9,10);
list($blues, $red) = array_chunk($dmgs, 5);

$blue_team_dmg = array_sum($blues);
$red_team_dmg = array_sum($red);

$blue_percents = array();
$red_percents = array();

foreach ($blues as $dmg) {
  $blues_percents[] = round($dmg / $blue_team_dmg * 100, 2);
}

foreach ($red as $dmg) {
  $red_percents[] = round($dmg / $red_team_dmg * 100, 2);
}

$dmgpercantages = array_merge($blues_percents, $red_percents);

result:

array(10) {
  [0] =>
  double(6.67)
  [1] =>
  double(13.33)
  [2] =>
  double(20)
  [3] =>
  double(26.67)
  [4] =>
  double(33.33)
  [5] =>
  double(15)
  [6] =>
  double(17.5)
  [7] =>
  double(20)
  [8] =>
  double(22.5)
  [9] =>
  double(25)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download