我有一个像
这样的数组//$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
)
但我无法找到找到每月平均值的方法。就我而言,有December 2012
的31个实例,November 2012
的31个实例和October 2012
的25个实例。因此,我需要掌握这些31
,31
和25
值,以便我可以将该月份除以该数字。
我认为必须在if(isset($abc[$month]))
循环中完成一些事情才能捕获但到目前为止还没有成功。还有其他方法可以获得平均值吗?
PS:我无法对月份名称(十月,十一月,十二月)进行硬编码以进行比较。他们会定期更换。
答案 0 :(得分: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);
}
答案 1 :(得分: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);