在php中usort()函数如何工作 [英] In php how does usort() function works
问题描述
我看过php文档,在线教程,但都没有找到usort如何实际工作.我下面有一个例子.
I have looked at the php documentation, tutorials online and none of them how usort is actually working. I have an example i was playing with below.
$data = array(
array('msg' => 'some text','month' => 11,'level' => 10),
array('msg' => 'some text','month' => 5,'level' => 10),
array('msg' => 'some text','month' => 8,'level' => 10),
array('msg' => 'some text','month' => 12,'level' => 10),
array('msg' => 'some text','month' => 2,'level' => 10),
array('msg' => 'some text','month' => 3,'level' => 10),
array('msg' => 'some text','month' => 4,'level' => 10),
array('msg' => 'some text','month' => 7,'level' => 10),
array('msg' => 'some text','month' => 10,'level' => 10),
array('msg' => 'some text','month' => 1,'level' => 10),
array('msg' => 'some text','month' => 6,'level' => 10),
array('msg' => 'some text','month' => 9,'level' => 10)
);
我希望能够将月份从12排序为1(因为它们是无组织的) 通过一些帮助,这就是解决方案
I wanted to be able to sort the months from 12 to 1 (since their unorganized) through some help this was the solution
function cmp($a, $b)
{
if ($a["month"] == $b["month"])
{
return 0;
}
return ($a["month"] < $b["month"]) ? -1 : 1;
}
usort($data, "cmp");
但是我不明白函数cmp如何对数组进行排序.我试图像这样打印出每个变量$ a和$ b:
but i dont understand how the function cmp sorts the array. i tried printing out each variable $a and $b like this:
function cmp($a, $b)
{
echo "a: ".$a['month']."<br/>";
echo " b: ".$b['month']."<br/>";
echo "<br/><br/>";
}
输出为
a: 3
b: 5
a: 9
b: 3
a: 3
b: 8
a: 6
b: 3
a: 3
b: 12
a: 1
b: 3
a: 3
b: 2
a: 10
b: 3
a: 3
b: 11
a: 7
b: 3
a: 4
b: 3
a: 12
b: 2
a: 5
b: 12
a: 12
b: 11
a: 8
b: 12
a: 5
b: 8
a: 2
b: 11
a: 6
b: 9
a: 7
b: 6
a: 6
b: 4
a: 10
b: 6
a: 1
b: 6
a: 9
b: 4
a: 7
b: 1
a: 10
b: 7
对于排序如何工作以及为什么使用cmp($ a,$ b)没有意义.如您所见,我已经尝试打印出其所有流程,但尚未对所有流程进行任何解决..
it makes no sense to how the sort is working and why cmp($a, $b) is used. i have tried to print out all its processes as you can see but have not come to any solution to how it all works..
谢谢
推荐答案
函数cmp
本身不进行排序.它只是告诉usort
一个值是否小于,等于或大于另一个值.例如.如果$a = 5
和$b = 9
,它将返回1表示$b
中的值大于$a
中的值.
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
.
排序由usort
完成.
这篇关于在php中usort()函数如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!