谁还没个明天 2010-11-26 03:50 采纳率: 50%
浏览 338
已采纳

按对象字段排序对象数组

How can I sort this array of objects by one of its fields, like name or count ?

  Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [name] => Mary Jane
            [count] => 420
        )

    [1] => stdClass Object
        (
            [ID] => 2
            [name] => Johnny
            [count] => 234
        )

    [2] => stdClass Object
        (
            [ID] => 3
            [name] => Kathy
            [count] => 4354
        )

   ....

转载于:https://stackoverflow.com/questions/4282413/sort-array-of-objects-by-object-fields

  • 写回答

17条回答 默认 最新

  • 7*4 2010-11-26 03:53
    关注

    Use usort, here's an example adapted from the manual:

    function cmp($a, $b)
    {
        return strcmp($a->name, $b->name);
    }
    
    usort($your_data, "cmp");
    

    edits imported from comments:

    If you're sorting the array from inside the class and your sorting function cmp is also defined inside the class, then use this:

    usort($your_data, array($this, "cmp"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(16条)

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器