2

我有一个数组,例如

//$ary, $ary contains some 80 entries, I'm showing only the first 10
Array
(
    [0] => Array
        (
            [December 2012] => 58
        )
    [1] => Array
        (
            [November 2012] => 84
        )
    [2] => Array
        (
            [December 2012] => 83
        )
    [3] => Array
        (
            [November 2012] => 72
        )
    [4] => Array
        (
            [November 2012] => 47
        )
    [5] => Array
        (
            [December 2012] => 93
        )
    [6] => Array
        (
            [November 2012] => 79
        )
    [7] => Array
        (
            [October 2012] => 70
        )
    [8] => Array
        (
            [November 2012] => 75
        )
    [9] => Array
        (
            [October 2012] => 59
        )
    [10] => Array
        (
            [December 2012] => 67
        )
)

我可以使用以下方法获得每个月的总数:

foreach($ary as $array)
{   
    foreach($array as $month=>$cent)
    {

        if(isset($abc[$month])) // prevent index warning
        {           
            $abc[$month] += $cent;
           // tried using $abc[$month] = $abc[$month]/2 but wrong values were returned
        }
        else
        {
            $abc[$month] = $cent;
        }
    }
}

这导致

Array
(
    [December 2012] => 2195
    [November 2012] => 2159
    [October 2012] => 1631
)

但我无法找到一种方法来找到每个月的平均值。就我而言,有 31 个实例December 2012、31 个实例November 2012和 25 个实例October 2012。因此,我需要掌握这些313125值,以便我可以将一个月除以该数字。

我在想必须在if(isset($abc[$month]))循环内做一些事情来捕获,但到目前为止还没有成功。有没有其他方法可以得到平均值?

PS:为了比较的目的,我不能硬编码月份的名称(十月、十一月、十二月)。它们会定期更换。

4

2 回答 2

1
$eachMonth = array();
foreach($ary as $array)
{   
   foreach($array as $month=>$cent)
  {

    $eachMonth[$month][] = $cent;

    if(isset($abc[$month])) // prevent index warning
    {           
        $abc[$month] += $cent
    }
    else
    {
        $abc[$month] = $cent;
    }
  }
}

然后每个月你可以计算平均值:

foreach( $eachMonth as $month => $values)
{
   echo $month.' : '.$abc[$month] / count($values);

}
于 2013-03-21T08:55:08.583 回答
1

试试这个 :

$your_array = array(array("December 2012" => 58),
               array("December 2012" => 58)
              );

$res    = array();            
foreach($your_array as $val){
  $res[key($val)][] = $val[key($val)];
}

foreach($res as $k=>&$v){
   $v    = array_sum($v)/count($v);
}

echo "<pre>";
print_r($res);
于 2013-03-21T08:58:37.240 回答