使用以下代码获取数组的最小值

时间:2019-01-26 05:47:05

标签: php

我不太了解以下内容的逻辑:

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

});

这将返回数组中的最大值。只要是数字,如何修改上面的代码以返回最小值?这将有助于我理解其工作原理。我知道或最小和最大功能。 预先感谢

3 个答案:

答案 0 :(得分:0)

然后应该分解代码,并学习调试所拥有的内容。这是一段非常简单的代码:

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

可以解决这个问题(有点bug),但是会令人困惑,因为您亲自调用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;
});

答案 1 :(得分:-1)

以下代码可以完成工作。它比较数组中两个位置的值,删除它们,然后存储最小值。因此,在每个步骤中将数组大小减小1,并继续重复该过程,直到数组大小变为1。

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

});

答案 2 :(得分:-1)

$min = array_reduce($values, function($carry, $i) {
    if (is_numeric($carry) && $i > $carry ) {
        return $carry;
    }
    return $i;

});