dongliyan9190 2015-06-08 11:42
浏览 59
已采纳

使用对象属性上的对象对数组进行排序

I would like to sort an array of objects by a property of the specific object. This is my array with objects:

enter image description here

As you can see I have an array $all_studies with 2 objects. How can I now sort on the graduationYear property of the objects? So I would like to have an array with objects and the the order with object 2010 first, then 2014, ... (in this case the order is already correct but this won't always be the same ..).

This is what I've tried but with no succes:

$all_studies = usort($all_studies, "sort_objects_by_graduationyear");

function sort_objects_by_graduationyear($a, $b) {
    if((int)$a->graduationYear == (int)$b->graduationYear){ return 0 ; }
    return ($a->graduationYear < $b->graduationYear) ? -1 : 1;
}

But I just get true back. I've never used the usort function so I don't really know how to work with it. Can someone help me?

  • 写回答

2条回答 默认 最新

  • dongzi0857 2015-06-08 11:48
    关注

    The function usort returns "true" on success. So, good news :).

    If you want to check if the sort is done, you only have to check your $all_studies object after the usort.

    $status = usort($all_studies, "sort_objects_by_graduationyear");
    print_r($all_studies);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!