在 php 中 usort() 函数是如何工作的 [英] In php how does usort() function works

查看:23
本文介绍了在 php 中 usort() 函数是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了 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() 函数是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆