我有多个数组,每个数组包含不同的键以及类似的键。
我需要获取每个键的值并对其进行平均。 理想情况下,我想返回一个包含唯一键和每个键的平均值的数组。
[0] => Array
(
[Armstrong_Tony] => 7
[Blair_Jarryd] => 7
[Broomhead_Tim] => 11
)
[1] => Array
(
[Armstrong_Tony] => 19
[Ball_Luke] => 20
[Blair_Jarryd] => 20
[Broomhead_Tim] => 23
)
[2] => Array
(
[Ball_Luke] => 20
[Beams_Dayne] => 14
[Blair_Jarryd] => 19
[Frost_Jack] => 8
[Goldsack_Tyson] => 7
)
这是我尝试过的。它获取密钥并将所有值添加到它自己的数组中。但这显然不是最佳解决方案。
$arr = array_merge_recursive($games[0],$games[1],$games[2],$games[3],$games[4]);
ksort($arr);
foreach($arr as $player => $val) {
if(array_key_exists($player, $games[0])) {
$prev_game_0 = $games[0][$player];
} else {
$prev_game_0 = "";
}
if(array_key_exists($player, $games[1])) {
$prev_game_1 = $games[1][$player];
} else {
$prev_game_1 = "";
}
if(array_key_exists($player, $games[2])) {
$prev_game_2 = $games[2][$player];
} else {
$prev_game_2 = "";
}
if(array_key_exists($player, $games[3])) {
$prev_game_3 = $games[3][$player];
} else {
$prev_game_3 = "";
}
if(array_key_exists($player, $games[4])) {
$prev_game_4 = $games[4][$player];
} else {
$prev_game_4 = "";
}
$last_5_array[$player] = array($prev_game_0, $prev_game_1, $prev_game_2, $prev_game_3, $prev_game_4);
}
答案 0 :(得分:2)
这应该可以帮助您获得所有密钥和所有平均值:
这里我遍历每个innerArray并在将它们保存在数组中之后获取所有键值我奉承数组并且只获取唯一值
之后我使用array_column()
(对于PHP +5.5),count()
和array_sum()
来计算平均值。
<?php
$arr = array(
array(
"Armstrong_Tony" => 7,
"Blair_Jarryd" => 7,
"Broomhead_Tim" => 11
),
array(
"Armstrong_Tony" => 19,
"Ball_Luke" => 20,
"Blair_Jarryd" => 20,
"Broomhead_Tim" => 23
),
array(
"Ball_Luke" => 20,
"Beams_Dayne" => 14,
"Blair_Jarryd" => 19,
"Frost_Jack" => 8,
"Goldsack_Tyson" => 7
)
);
$keys = array();
$average = array();
//Get Keys
foreach($arr as $innerArray)
$keys[] = array_keys($innerArray);
$keys = array_unique(call_user_func_array('array_merge', $keys));
//Get average
foreach($keys as $key) {
$values = array_column($arr, $key);
$average[$key] = array_sum($values) / count($values);
}
print_r($average);
?>
输出:
Array
(
[Armstrong_Tony] => 13
[Blair_Jarryd] => 15.333333333333
[Broomhead_Tim] => 17
[Ball_Luke] => 20
[Beams_Dayne] => 14
[Frost_Jack] => 8
[Goldsack_Tyson] => 7
)
答案 1 :(得分:1)
您需要创建一个数组,其中包含每个键的总和和计数(键在所有数组中出现的次数)。一旦你通过数组编译了这个信息循环并将总和除以计数就可以得到平均值。
$myArrays = array(
array('Armstrong_Tony' => 2),
array('Ball_Luke' => 3),
);
$sums = array();
foreach($myArrays as $array) {
foreach($array as $key => $value) {
if(!isset($sums[$key]))
$sums[$key] = array('count' => 0, 'sum' => 0);
$sums[$key]['count']++;
$sums[$key]['sum'] += $value;
}
}
$results = array();
foreach($sums as $key => $sum) {
$results[$key] = $sum['sum']/$sum['count'];
}
print_r($results);