php - 如何垂直获取数组的最大值?
问题描述
我有这种数据结构
$scores = [
'user_a' => [75, 67, 80, 90, 20, 80],
'user_b' => [65, 70, 80, 90, 20, 80],
'user_c' => [56, 70, 75, 80, 50, 70],
'user_d' => [40, 50, 89, 56, 45, 78],
'user_e' => [60, 80, 90, 78, 80, 76],
];
我想从每个垂直方向获得最大user_a
数量user_e
。我期待的是这样的:
$max = [75, 80, 90, 90, 80];
我试过这个,但是这个数字是按键水平取的。
$max = [];
foreach ($scores as $score) {
array_push($max, max($score));
}
var_dump($max); // [90, 90, 80, 89, 90];
实现这一目标的正确方法是什么?
解决方案
如果您需要对映射值进行更多控制,这是我的解决方案。
<?php
$scores = [
'user_a' => [75, 67, 80, 90, 20, 80],
'user_b' => [65, 70, 80, 90, 20, 80],
'user_c' => [56, 70, 75, 80, 50, 70],
'user_d' => [40, 50, 89, 56, 45, 78],
'user_e' => [60, 80, 90, 78, 80, 76],
];
// Get vertical score lines
$verticalScores = array_reduce($scores, function($carry, $score) {
foreach($score as $key => $value) {
$carry[$key][] = $value;
}
return $carry;
}, []);
// Get max score per vertical line
$maxScores = array_map('max', $verticalScores);
var_dump($maxScores); //75, 80, 90, 90, 80, 80
推荐阅读
- sql - 如何在列中选择值 A 或同时选择 A 和 B 但不选择 B?
- ruby-on-rails - 在控制器中保存记录后如何触发动作
- gis - 如何在道路形状文件和特定区域创建一定数量的海龟?
- nativescript - Nativescript iOS App Delegate 方法未触发
- python - Python * 关于参数(不是 args 或 kwargs)
- java - Unable to find match between the canonical context path and the URI presented by the user agent
- java - 如何检索本地化的 Linkedin 登录页面
- javascript - 如何设置水平滚动位置反应
- build - 有什么图书馆可以构建不同语言的 AFP 文件?
- java - Spring security OAuth2 在使用 SockJS 时不保护 websocket 端点?