php 对多维数组进行排序,但从 1 开始索引

标签 php arrays sorting multidimensional-array usort

我有一个多维数组,我想根据“评级”进行排序...但我也希望索引从 1 开始,这是我在手动创建这些数组时使用的。当我使用 usort 时,它会重新排列数组,但现在它们从索引 0 开始,所以我无法执行从 1 到 6 的循环,因为排序后 6 是未定义的。

从 1 开始 $array 会更干净,因此 $player[$i] 代表实际的玩家编号。这是我的数组在排序之前的样子

$player[1]['rating'] = 8
$player[2]['rating'] = 5
$player[3]['rating'] = 10

这是我的排序函数:

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

我称之为

usort($player, 'sortByRating');

最佳答案

最简单的方法是在usort之后添加此代码:

array_unshift($player,'temp');
unset($player[0]);

完整代码:

function sortByrating($a, $b) {
    return $a['rating'] - $b['rating'];
}

$player[1]['rating'] = 8;
$player[2]['rating'] = 5;
$player[3]['rating'] = 10;

usort($player, 'sortByRating');

array_unshift($player,'temp');
unset($player[0]);

print_r($player);

输出:

Array
(
    [1] => Array
        (
            [rating] => 5
        )

    [2] => Array
        (
            [rating] => 8
        )

    [3] => Array
        (
            [rating] => 10
        )

)

更新可能的解决方案:

function sortByrating($a, $b) {
    return $a['rating'] - $b['rating'];
}

$player[1]['rating'] = 8;
$player[2]['rating'] = 5;
$player[3]['rating'] = 10;

uasort($player, 'sortByRating');

foreach($player as $player_id=>$player_data) {
    $place++;
    $player[$player_id]['place'] = $place;
    $places[$place] = $player_id;
    echo "Player #{$player_id} takes Place #{$place}\n";
}

echo "\nPlayers array: ";
print_r($player);

echo "\nPlaces array: ";
print_r($places);

输出:

Player #2 takes Place #1
Player #1 takes Place #2
Player #3 takes Place #3

Players array: Array
(
    [2] => Array
        (
            [rating] => 5
            [place] => 1
        )

    [1] => Array
        (
            [rating] => 8
            [place] => 2
        )

    [3] => Array
        (
            [rating] => 10
            [place] => 3
        )

)

Places array: Array
(
    [1] => 2
    [2] => 1
    [3] => 3
)

关于php 对多维数组进行排序,但从 1 开始索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43991455/

相关文章:

php - Laravel firstOrNew 如何检查它是第一个还是新的?

php - 如何在单个查询中在两个表中插入数据?

c++ - Bjarne Stroustrup 的 C++ 编程和实践第 2 版中的单参数排序

php - 如何使用 https-post 将 node.js 的 POST 请求发送到 php 页面?

php - 修改先前回显的变量

javascript - 从数组中删除特定项目,未按预期工作

javascript - 如何检查一个对象数组是否包含另一个对象数组的所有ID JS

javascript - 如何按给定的组数创建一系列数字的通讯组

java - HashMap 与 ArrayList

java - 排序 ListView Java