問題描述
我已經查看了 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
中的值大于 $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
.
排序由usor
完成.
這篇關于在 php 中 usort() 函數是如何工作的的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!