【问题标题】:Sort after an array value that is child of the array在作为数组子元素的数组值之后排序
【发布时间】:2012-04-05 10:06:14
【问题描述】:

我尝试搜索并找到了这个:

Sort an array by a child array's value in PHP

但该功能在我的情况下不起作用:

                $sorted = array();
                foreach($players as $player)
                {
                    $p = Model::factory('user');
                    $p->load($player['id']);

                    $sorted[] = array('id' => $player['id'], 'username' => $p->get_username());
                }

如何在用户名后按字母顺序对数组进行排序?

函数,

function cmp($a, $b) {
        if ($a['username'] == $b['username']) {
                return 0;
        }
        return ($a['username'] < $b['username']) ? -1 : 1;
}

然后调用 usort($sorted,"cmp");对我不起作用(出现错误未定义索引 [2])..

有没有办法选择是降序还是升序?

【问题讨论】:

  • 使用正确的索引(你想要排序的值的索引)——而不是[2]
  • 使用username 而不是2
  • @karem - 检查我的答案

标签: php arrays


【解决方案1】:

'cmp' 函数将是:

// $param - the parameter by which you want to search
function cmp(&$a, &$b, $param) {
    switch( $param ) {
        case 'id':
            if ( $a['id'] == $b['id'] ) {
                return 0;
            }

            return ( $a['id'] < $b['id'] ) ? -1 : 1;
            break;
        case 'username':
            // string comparison
            return strcmp($a['username'], $b['username']);
            break;
    }
}

// this is the sorting function by using an anonymous function
// it is needed to pass the sorting criterion (sort by id / username )
usort( $sorted, function( $a,$b ) {
    return cmp( $a, $b, 'username');
});

【讨论】:

  • 我不能将参数传递给 cmp 函数,所以我可以提一下要查找的索引吗?在此代码中,“用户名”。所以 usort($sorted, cmp('username'));然后如果我想查找 id ,则 usort($sorted, cmp('id'));等?
  • 感谢您的回复。我该怎么称呼它? usort($sorted, cmp('用户名'));不会解决
  • @karem - 我已修改我的答案以包含比较过滤器。基本上,它使用了 PHP 中的 **anonymous(lambda) 函数**link。您必须拥有 php 版本 >= 5.3
【解决方案2】:

因为您的数组中不存在索引 2。你应该使用 $a['username'] 或 $a['id'],但我想你想按用户名排序,所以你会使用 $a['username']。

【讨论】:

    猜你喜欢
    • 2022-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多