首页 > 解决方案 > 使用以下代码获取数组的最小值

问题描述

我真的不明白以下的逻辑:

$max = array_reduce($values, function($max, $i) {
    if (is_numeric($i) && $i > $max) {
        return $i;
        //echo $i."max";
    }
    return $max;

});

这将返回数组中的最大值。只要是数字,我如何修改上面的代码以返回最小值?这将帮助我理解这是如何工作的。我知道或最小和最大功能。提前致谢

标签: php

解决方案


然后你应该分解代码并学习调试你拥有的东西。这是一段非常直接的代码:

// 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;
});

推荐阅读