我是PHP开发的新手,我有一个任务来查找多维数组的每日平均值。由于我从未做过类似的事情,所以我不知道如何做到这一点。任何帮助将深表感谢。这是一段代码:
PrintWriter out = new PrintWriter(source);
out.print("I hate Mondays");
out.close();
我需要这种格式的答案:
<?php
$measurements = array(
'1_DAY_2017' => array('humidity' => array(15,15,15,15,7,16,11,2), 'temperature' => array(32,28,27,26,24,24,28,31)),
'2_DAY_2017' => array('temperature' => array(26,24,24,28,28,26), 'precipitation' => array(12,15,10,12,7,4,2)),
'3_DAY_2017' => array('humidity' => array(16,12,15,15,7,16,11,2), 'temperature' => array(32,28,27,26,24,24,28)),
'4_DAY_2017' => array('humidity' => array(11,11,15,15,7,16,10,2), 'temperature' => array(26,24,24,28,31,31,28,26)),
'5_DAY_2017' => array('humidity' => array(12,15,10,12,7,16,2), 'temperature' => array(25,24,24,28,31,30,27,26)),
'6_DAY_2017' => array('humidity' => array(15,11,13,12,7,16,11,2), 'temperature' => array(25,24,23,28,31,31,27,26)),
'7_DAY_2017' => array('humidity' => array(14,15,15,15,7,16,11,2), 'temperature' => array(26,24,24,28,32,31,28,27)),
);
我希望它会有所帮助。
答案 0 :(得分:0)
$result = [];
foreach ($measurements as $day => $data) {
foreach ($data as $measurement_type => $values) {
$result[$day][$measurement_type] = array_sum($values) / count($values);
}
}
输出:
Array
(
[1_DAY_2017] => Array
(
[humidity] => 12
[temperature] => 27.5
)
[2_DAY_2017] => Array
(
[temperature] => 26
[precipitation] => 8.8571428571429
)
[3_DAY_2017] => Array
(
[humidity] => 11.75
[temperature] => 27
)
...
答案 1 :(得分:0)
显式:
<?php
$measurements = array(
'1_DAY_2017' => array('humidity' => array(15,15,15,15,7,16,11,2), 'temperature' => array(32,28,27,26,24,24,28,31)),
'2_DAY_2017' => array('temperature' => array(26,24,24,28,28,26), 'humidity' => array(12,15,10,12,7,4,2)),
);
$average = function(array $nums)
{
return array_sum($nums)/count($nums);
};
$averages = [];
foreach($measurements as $key => $value)
{
$averages[$key]['humidity'] = $average($value['humidity']);
$averages[$key]['temperature'] = $average($value['temperature']);
}
var_export($averages);
输出:
array (
'1_DAY_2017' =>
array (
'humidity' => 12,
'temperature' => 27.5,
),
'2_DAY_2017' =>
array (
'humidity' => 8.857142857142858,
'temperature' => 26,
),
)