douxi2011 2012-10-16 10:13
浏览 199

在php中对对象数组进行排序

HI i want to sort an array of objects , it is in the form of array which has objects and each objects has key,value , i want to sort the objects based on value, the problem is the values contains the numbers which have spaces in between, and some are empty numbers too, so I am not able to sort it using usort any help would be appreciated.

here's a code snippet

array(4) {
  [0]=>
  object(stdClass)#308 (2) {
    ["key"]=>
    string(2) "AF"
    ["value"]=>
    string(3) "093"
  }
  [1]=>
  object(stdClass)#306 (2) {
    ["key"]=>
    string(2) "AL"
    ["value"]=>
    string(3) "355"
  }
  [2]=>
  object(stdClass)#304 (2) {
    ["key"]=>
    string(2) "DZ"
    ["value"]=>
    string(3) "213"
  }
  [3]=>
  object(stdClass)#302 (2) {
    ["key"]=>
    string(2) "AS"
    ["value"]=>
    string(5) "1 684"
  }

}

I want the result to be sorted based on the value.

  • 写回答

3条回答 默认 最新

  • dongsha7215 2012-10-16 10:18
    关注

    You can use

    usort($list, function ($a, $b) {
        $a = filter_var($a->value,FILTER_SANITIZE_NUMBER_INT);
        $b = filter_var($b->value,FILTER_SANITIZE_NUMBER_INT);
        return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分