首页 > 解决方案 > 如何垂直获取数组的最大值?

问题描述

我有这种数据结构

$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

解决方案


如果您需要对映射值进行更多控制,这是我的解决方案。

<?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

推荐阅读