php - 使用以下代码获取数组的最小值
问题描述
我真的不明白以下的逻辑:
$max = array_reduce($values, function($max, $i) {
if (is_numeric($i) && $i > $max) {
return $i;
//echo $i."max";
}
return $max;
});
这将返回数组中的最大值。只要是数字,我如何修改上面的代码以返回最小值?这将帮助我理解这是如何工作的。我知道或最小和最大功能。提前致谢
解决方案
然后你应该分解代码并学习调试你拥有的东西。这是一段非常直接的代码:
// array_reduce — Iteratively reduce the array to a single value using a callback function
//A callback is literally a function that is called for the logic and is started at function
//$values is your values, max is what was run from the last iteration and i is the current value.
$max = array_reduce($values, function($max, $i) {
// Checking the value is numeric
// AND
// $i is greater than $max
if (is_numeric($i) && $i > $max) {
// If the above is true you have a number greater than the current
// max value return this iteration value.
return $i;
//echo $i."max";
}
// It will only reach here is the above is not true so return what was the max
// example max = 5 i = 2 you will return 5
return $max;
});
因此,您需要找到在该逻辑中获得最大值的逻辑:
if (is_numeric($i) && $i > $max) {}
现在你怎样才能使它成为最小的井 > 更大而 < 更小:
if (is_numeric($i) && $i < $max) {}
会做的伎俩(有一种错误),但令人困惑,因为你亲自调用 var max 我会像这样重写:
$min = array_reduce($values, function($min, $value) {
//Has to check for a null min sets min to value if smaller
if ((is_numeric($min) && $value < $min) || $min == null) {
$min = $value;
//echo $value."min";
}
return $min;
});
推荐阅读
- android - 如何将相机基本照片中的照片保存在数据库中?
- excel - 从“ThisWorkbook”问题中复制
- gitlab - Gitlab CI/CD 作业的日志超出限制
- java - 当 Junit 使用 Gradle 测试成功时自动提交 Git
- android - 如何捕获股票 Android Clock 应用程序事件?
- reactjs - 在单个组件中使用多个 redux 连接 HOC
- javascript - 未捕获的类型错误:无法在我的 php 文档上设置 null 的属性“值”
- c# - Visual Studio 自动恢复 dll 包
- outlook - Outlook 2013 将超过 n 个月的邮件移动到 pst
- java - Java 8 - 从 Collection.stream.map() 调用多参数方法