【问题标题】:How does this callback example (php manual) work?这个回调示例(php 手册)是如何工作的?
【发布时间】:2012-01-24 22:09:27
【问题描述】:

在下面来自http://php.net/manual/en/function.usort.php 的示例中,调用了一个回调函数。

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$x = array(3, 2, 5, 6, 1);

usort($x, "cmp");

foreach ($x as $key => $value) {
    echo "$key: $value<br>";
}

我对 usort 并不特别感兴趣,但它在示例中。我的问题是, cmp 函数的 $a 和 $b 参数是什么? usort 被赋予 $x 这是一个数组,所以我不明白 cmp 中发生了什么(代码很简单,但我不知道参数是什么)。

我的想象力告诉我 $a 和 $b 都以某种方式迭代数组(唯一可以排序的方式)。有人可以解释一下吗?

【问题讨论】:

    标签: php function callback usort


    【解决方案1】:

    它们是数组中被相互比较的两个元素。如果两个元素相等,比较函数应该返回 0,如果 $a $b

    则返回大于 0

    php.net Example #2 usort() example using multi-dimensional array 上的第二个例子更能说明这一点。

    由于每个数组索引都是一个数组本身,可能包含许多元素,它允许您根据所需的索引对数组进行排序。

    在这些情况下,您只需要知道回调期望接收 2 个值进行比较,因为要对数组进行排序,您一次比较 2 个元素,直到列表被排序。有关排序算法的更多信息,请参阅 QuicksortBubble sort

    <?php
    function cmp($a, $b)
    {
        // usort gives 2 values from the array to compare, $a and $b
        // we compare the "fruit" index from each item so the array is
        // ultimately sorted by fruit
        return strcmp($a["fruit"], $b["fruit"]);
    }
    
    $fruits[0]["fruit"] = "lemons";
    $fruits[1]["fruit"] = "apples";
    $fruits[2]["fruit"] = "grapes";
    
    usort($fruits, "cmp");
    
    while (list($key, $value) = each($fruits)) {
        echo "\$fruits[$key]: " . $value["fruit"] . "\n";
    }
    

    【讨论】:

    • 谢谢draw010。我现在明白了——但我很好奇你是怎么想出来的,因为手册中对函数的定义对我来说不是很清楚:The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
    • 比较函数使用与PHP函数strcmp()相同的返回值,这也是从C中借来的,所以我熟悉这个函数的工作原理。那里不是很清楚,但是如果您查看 strcmp 可能会更清楚一些。
    猜你喜欢
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2016-01-21
    • 2019-06-15
    相关资源
    最近更新 更多