我有一个包含名称和整数值的二维数组。行中并不总是包含所有名称。我需要按名称对数据进行分组,并求出每组中所有值的平均值。
样品阵列:
$games = [
[
"Armstrong_Tony" => 7,
"Blair_Jarryd" => 7,
"Broomhead_Tim" => 11
],
[
"Armstrong_Tony" => 19,
"Ball_Luke" => 20,
"Blair_Jarryd" => 20,
"Broomhead_Tim" => 23
],
[
"Ball_Luke" => 20,
"Beams_Dayne" => 14,
"Blair_Jarryd" => 19,
"Frost_Jack" => 8,
"Goldsack_Tyson" => 7
]
];
预期结果:
[
'Armstrong_Tony' => 13,
'Blair_Jarryd' => 15.333333333333334,
'Broomhead_Tim' => 17,
'Ball_Luke' => 20,
'Beams_Dayne' => 14,
'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);
}
3条答案
按热度按时间jk9hmnmh1#
这应该适用于您获取所有关键点和所有平均值:
在这里,我遍历每个innerArray并获取所有键值,然后将它们保存到一个数组中,我对该数组进行了扁平化,只获取唯一值
然后我使用
array_column()
(对于PHP +5.5),count()
和array_sum()
来计算平均值。输出:
qnzebej02#
你需要创建一个包含每个键的总和和计数(键在所有数组中出现的次数)的数组。一旦你编译了这些信息,循环数组,用总和除以计数得到平均值。
zsbz8rwp3#
作为一种现代的优雅方法,首先使用
array_merge_recursive()
和spread操作符按关联键对数据进行分组,然后在array_map()
中将分组数据转换为数组(因为单独的值不会形成子数组),然后进行array_sum()
和count()
的标准调用。代码:(Demo)
或者使用PHP7.4的箭头函数: