In php how does usort() function works

巧了我就是萌 提交于 2019-11-27 19:24:49

The function cmp itself doesn't do the sorting. It just tells usort if a value is smaller, equal or greater than another value. E.g. if $a = 5 and $b = 9 it will return 1 to indicate that the value in $b is greater than the one in $a.

Sorting is done by usort.

The callback provided to the sorting functions in PHP have three return values:

0:  both elements are the same
-1 (<0): the first element is smaller than the second
1 (>0):  the first element is greater

Now, usort probably uses some kind of quicksort or mergesort internally. For each comparison it calls your callback with two elements and then decides if it needs to swap them or not.

usort() uses an implementation of Quicksort to sort the array, it calls your cmp function as many times as it needs to to fully sort the array using that algorithm.

As the others mentioned, usort uses the Quicksort algorithm. On a side note, you do not need to explicitly do the comparision between two strings. You can use PHP's string compare methods.

The function that you created,

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

could simply be written as follows

function compareMyStrings($a, $b){
    return strnatcmp($a["month"], $b["month"]);
}

Hope this helps!

This is another solution I found

<?php 
$users = array( array( "peter", "male", "46"), 
                array( "hans", "male", "19"), 
                array( "john", "male", "30"), 
                array( "linda", "female", "54"), 
                array( "erika", "female", "79")); 
usort($users, "whatevername"); 
function whatevername($whatever1, $whatever2) 
{ 
    // $whatever1 and $whatever2 are items from the $user array. 
    // index [2] is the age. 
    // Check if $whatever1 is older than $whatever2. 
    // Return 1 tells usort to swap the positions. 
    return $whatever1[2] > $whatever2[2]; 
} 

echo("<pre>"); 
print_r($users); 
echo("</pre>"); 
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!