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);
    });
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题