dongzhimin2231 2015-01-31 21:48
浏览 36
已采纳

按属性排序php数组的最简单方法

I tried some of the methods from this post: Sort array by object property in PHP?

But I am not able to sort by the last name of my person array in wordpress.

Here is what I do:

<?php 
    function personSort( $a, $b ) {
        return $a->last_name == $b->last_name ? 0 : ( $a->last_name > $b->last_name ) ? 1 : -1;
    }

    usort( $autlist, 'personSort' );
    foreach($autlist as $al){ ?>
        <option value="<?php echo $al->ID; ?>"><?php echo $al->first_name.' '.$al->last_name; ?></option>

The order comes out like this:

Nick Hammond
Peter Ruck
Nam Ol Lamon

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • douwei8672 2015-01-31 21:56
    关注

    You cannot compare strings using the < and > comparison operators, they are reserved for numbers in PHP. If you do, your strings are transparently type-casted to numbers first, probably all evaluating to 0, hence the seemingly random result.

    Try using strcmp(), which compares strings and returns a number, just like what usort() expects:

    function personSort( $a, $b ) {
        return strcmp($a->last_name, $b->last_name);
    }
    

    Note that starting with PHP 5.3, you can avoid declaring a function in the global scope, and use an anonymous function instead:

    usort($autlist, function ($a, $b) {
        return strcmp($a->last_name, $b->last_name);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题