php - 执行 min 和 max 后如何在 php 数组中显示超过 1 个数据
问题描述
我正在做作业,但在执行 min 和 max 语法后,我找不到在数组中显示多个结果的解决方案
我的老师说我应该使用min
并max
显示超过 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
解决方案
我的两分钱:
$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>';
推荐阅读
- c# - 即使我做的一切正确,显示按钮也不显示任何内容(我认为)
- php - CodeIgniter:未定义的变量从 __construct() 获取
- twitter-bootstrap - Bootstrap 按钮故障排除
- python-3.x - AttributeError: module 'datetime' has no attribute 'today' error while using Selenium GeckoDriver and Firefox through Python
- swift - Flutter Channel 方法字符串不能作为 URL 工作
- c++ - 无法读取 FAT32 隐藏扇区数
- .net - 获取不记名令牌 - Oauth 2
- python - 在 Python 中跳过不需要的日期时绘制时间与日期
- android - 如何使用 TypeScript 在 React Native 中编写正确的 `Keyboard.addListener`?
- c++ - 如何从 Terralang 扩展 C++ 类?