在作为数组子级的数组值之后排序


Sort after an array value that is child of the array

我试图搜索并找到这个:

在 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])。

有没有办法选择它应该是降序还是升序排序?

'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');
});

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