duanchi4184
2016-09-09 14:15
浏览 15
已采纳

php数组中某些值的总和[关闭]

I have this array`

<?php
$arr = [['name'=>'john','age'=>20,'sex'=>'m'],
        ['name'=>'maria','age'=>12,'sex'=>'f'],
        ['name'=>'nick','age'=>25,'sex'=>'m'],
        ['name'=>'jo','age'=>31,'sex'=>'f'],];
foreach ($arr as $persoana) {
  foreach ($persoana as $id=>$value) {
    if ($id == 'age') {
        $sumvarsta = $sumvarsta + $value;
        $n++;
    }
  }
}`?>

i need total average age (total average age seems to be working ok) , average age for women and average age for men. How to calculate ?

thx.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douduan4116 2016-09-09 14:32
    已采纳
    <?php
    $arr = [['name'=>'john','age'=>20,'sex'=>'m'],
            ['name'=>'maria','age'=>12,'sex'=>'f'],
            ['name'=>'nick','age'=>25,'sex'=>'m'],
            ['name'=>'jo','age'=>31,'sex'=>'f'],];
    
    $womansum = 0;
    $womancount = 0;
    $mansum = 0;
    $mancount = 0;
    
    foreach ($arr as $persoana) {
    
      if ($persoana['sex'] == 'm')
      {
        $mansum += $persoana['age'];
        $mancount++;
      } else {
        $womansum += $persoana['age'];
        $womancount++;
      }
    
    }
    
    $manAverage = $mansum / $mancount;
    
    $womanAverage = $womansum / $womancount;
    
    $totalAverage = ($mansum + $womansum) / ($mancount + $womancount);
    
    
    ?>
    
    点赞 打赏 评论

相关推荐 更多相似问题