PHP排序多维数组usort() [英] PHP sort multidimensional array usort()

查看:96
本文介绍了PHP排序多维数组usort()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的数组,并想按字母顺序按名称排序。我对如何使用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?

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!!

这应该更好。

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

这篇关于PHP排序多维数组usort()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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