PHP sort multidimensional array usort()

倖福魔咒の 提交于 2020-01-07 05:21:07

问题


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?

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');

回答1:


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);
}


来源:https://stackoverflow.com/questions/9276034/php-sort-multidimensional-array-usort

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!