Lotus@ 2010-11-26 03:50 采纳率: 100%
浏览 946
已采纳

按照对象字段对对象进行排序

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条回答 默认 最新

  • YaoRaoLov 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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料