首页 > 解决方案 > 执行 min 和 max 后如何在 php 数组中显示超过 1 个数据

问题描述

我正在做作业,但在执行 min 和 max 语法后,我找不到在数组中显示多个结果的解决方案

我的老师说我应该使用minmax显示超过 1 个结果

$temperatures = [78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73];
$max = max($temperatures);
$min = min($temperatures);

最终结果应该是:

平均温度:70.6
五个最低温度列表: 60、62、63、63、64
五个最高温度列表:76、78、79、81、85

标签: php

解决方案


我的两分钱:

$temperatures = [78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73];

# simply sum the elements then divide by count
$avg = (array_sum($temperatures) / count($temperatures));

# sort arr low -> high
sort($temperatures);
# make els unique
$temperatures = array_unique($temperatures);

$min = array_slice($temperatures, 0, 5); # get first 5 in array
$max = array_slice($temperatures, -5); # get last 5 in array

echo '<pre>'. print_r($avg, 1) .'</pre>';
echo '<pre>'. print_r($min, 1) .'</pre>';
echo '<pre>'. print_r($max, 1) .'</pre>';

推荐阅读