简体   繁体   English

PHP排序多维数组usort()

[英]PHP sort multidimensional array usort()

I have the below array and want to order it alphbetically by "Name". 我有下面的数组,想按字母顺序按“名称”排序。 I am a little confused on how to use the usort() function for this as what I have does not work, or is there a better function to use? 我对此如何使用usort()函数有些困惑,因为我所拥有的不起作用,还是有更好的函数使用?

Array (
    [0] => SimpleXMLElement Object
        (
            [id] => 1118809
            [Name] => Laptop
            [parentID] => 0
            [sequence] => 4
            [visible] => 1
        )

    [1] => SimpleXMLElement Object
        (
            [id] => 1109785
            [Name] => Special Offers
            [parentID] => 0
            [sequence] => 0
            [visible] => 1
        )

    [2] => SimpleXMLElement Object
        (
            [id] => 1118805
            [Name] => Printers
            [parentID] => 0
            [sequence] => 12
            [visible] => 0
        )

    [3] => SimpleXMLElement Object
        (
            [id] => 1092140
            [Name] => USB
            [parentID] => 0
            [sequence] => 14
            [visible] => 1
        ) )

function sort_cats_by_name($a, $b) {
    return   $a->Name  - $b->Name;
}

usort($subcats, 'sort_cats_by_name');

Ouch, substracting strings seems to be a strange way to do string comparisons , it could not work!! 哎呀,减去字符串似乎是进行字符串比较的一种奇怪方法,它不起作用!

This one should work much better. 这应该工作得更好。

function sort_cats_by_name($a, $b) {
   return   strcmp($a->Name,$b->Name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM