php数组中某些值的总和

时间:2016-09-09 14:15:44

标签: php arrays

我有这个数组`

<?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++;
    }
  }
}`?>

我需要总平均年龄(总平均年龄似乎正常),女性的平均年龄和男性的平均年龄。 怎么算?

THX。

1 个答案:

答案 0 :(得分:1)

<?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);


?>