这是一个非常深奥的问题,但我真的很好奇.我今天第一次使用usort,而且我对目前的情况特别感兴趣.假设我有以下数组:
$myArray = array(1, 9, 18, 12, 56);
Run Code Online (Sandbox Code Playgroud)
我可以用usort排序:
usort($myArray, function($a, $b){
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
});
Run Code Online (Sandbox Code Playgroud)
我不是100%清楚两个参数$ a和$ b的情况.它们是什么,它们代表什么.我的意思是,我可以假设$ a代表数组中的当前项目,但这与之相比究竟是什么?什么是$ b?
我可以增加我的数组以包含字符串:
$myArray = array(
array("Apples", 10),
array("Oranges", 12),
array("Strawberries", 3)
);
Run Code Online (Sandbox Code Playgroud)
并运行以下内容:
usort($myArray, function($a, $b){
return strcmp($a[0], $b[0]);
});
Run Code Online (Sandbox Code Playgroud)
这将根据[0]索引值按字母顺序对我的子数组进行排序.但是这并不能说明$ a和$ b是什么.我只知道匹配我正在寻找的模式.
有人可以提供一些关于实际发生的事情的清晰度吗?
Vin*_*vic 32
$ a和$ b的确切定义将取决于用于对数组进行排序的算法.要对任何东西进行排序,你必须有一种方法来比较两个元素,这就是回调函数的用途.一些排序算法可以从数组中的任何地方开始,其他排序算法只能在它的特定部分开始,所以在$ a和$ b中没有固定含义,除了它们是数组中必须根据当前算法进行比较的两个元素.
该方法可用于阐明PHP正在使用的算法.
<?php
$myArray = array(1, 19, 18, 12, 56);
function compare($a, $b) {
echo "Comparing $a to $b\n";
if ($a == $b) return 0;
return ($a < $b) ? -1 : 1;
}
usort($myArray,"compare");
print_r($myArray);
?>
Run Code Online (Sandbox Code Playgroud)
产量
vinko@mithril:~$ php sort.php
Comparing 18 to 19
Comparing 56 to 18
Comparing 12 to 18
Comparing 1 to 18
Comparing 12 to 1
Comparing 56 to 19
Array
(
[0] => 1
[1] => 12
[2] => 18
[3] => 19
[4] => 56
)
Run Code Online (Sandbox Code Playgroud)
从输出和查看源代码我们可以看到使用的排序确实是一个快速实现,检查PHP源代码中的Zend/zend_qsort.c(链接到版本有点旧,但没有太大变化).
它选择数组中间的枢轴,在这种情况下是18,然后它需要重新排序列表,以便所有比枢轴更少的元素(根据使用的比较函数)来到枢轴之前,所以所有大于枢轴的元素在它之后,我们可以看到它在将所有内容首先与18进行比较时这样做.
一些进一步的图解说明.
Step 0: (1,19,18,12,56); //Pivot: 18,
Step 1: (1,12,18,19,56); //After the first reordering
Step 2a: (1,12); //Recursively do the same with the lesser, here
//pivot's 12, and that's what it compares next if
//you check the output.
Step 2b: (19,56); //and do the same with the greater
要对任何东西进行排序,你需要一种方法来比较两个项目并找出一个是否先于另一个项目.这是你提供给我们的.此函数将从输入数组中传递两个项目,并返回它们应该处于的顺序.
一旦有了比较两个元素的方法,就可以使用sort-algorithm-of-choice.
如果您不熟悉,您可能希望了解像bubblesort这样的简单朴素算法如何使用比较函数.
在幕后,PHP正在使用快速排序.