php-将对象数组减少到“最佳10”

我有一系列对象,它们是足球运动员.数组可以包含从零到数千个播放器的任何内容.我想将其减少到最佳10.我的最初尝试如下:

while (count($ArrayOfPlayers) > 10) {

    $ArrayIndex = 0;
    $WorstPlayerIndex = -1;
    $WorstPlayerSkill = 9999999999;
    foreach ($ArrayOfPlayers as $Player) {
        $Skill = $Player->RatingsArray['Skill'];
        if ($Skill < $WorstPlayerSkill) {
            $WorstPlayerIndex = $ArrayIndex;
            $WorstPlayerSkill = $Skill;
        }
        $ArrayIndex += 1;
    }

    // Found the worst player in the list, so remove him.
    unset($ArrayOfPlayers[$WorstPlayerIndex]);
}

阅读了类似的文章后,我现在知道问题在于数组实际上并没有被更改,因此while循环会永远持续下去(计算机的确锁定了).

因此,根据其他帖子的建议,我尝试进行以下纠正.

while (count($ArrayOfPlayers) > 10) {

        $WorstIndexPlayer = 0;
        $WorstPlayerSkill = 9999999999;
        foreach ($ArrayOfPlayers as $key => &$Player) {
            $Skill = $Player->RatingsArray['Skill'];
            if ($Skill < $WorstPlayerSkill) {
                $WorstIndexPlayer = $key;
                $WorstPlayerSkill = $Skill;
            }
        }
        // Found the worst player in the list, so remove him.
        unset($ArrayOfPlayers[$WorstIndexPlayer]);
}

正如您可能会说的那样,我现在不了解我在做什么,也不了解$key部分的用途(只是从其他示例中复制而来).它仍然只是挂在PC上.

我该如何纠正这个问题,或者是否有更好的方法可以完全做到这一点?

为响应对数据结构的要求,这里仅转储了2个播放器,以显示它们的排列方式.

Array
(
[0] => Player Object
    (
        [ID] => 1
        [TeamID] => 1
        [Name] => Joseph Dorrington
        [RatingsArray] => Array
            (
                [Skill] => 51993
            )
    )

[1] => Player Object
    (
        [ID] => 2
        [TeamID] => 1
        [Name] => Oliver Tillyard
        [RatingsArray] => Array
            (
                [Skill] => 64574
            )

    )

解决方法:

使用usort,您可以首先按此值对数组进行排序,然后使用array_slice获取前10个元素:

function cmp($a, $b){
    if ($a->RatingsArray['Skill'] == $b->RatingsArray['Skill']) {
        return 0;
    }
    return ($a->RatingsArray['Skill'] > $b->RatingsArray['Skill']) ? -1 : 1;
}
usort($ArrayOfPlayers, "cmp");
$ArrayOfPlayers = array_slice($ArrayOfPlayers, 0, 10);
上一篇:哪个效率更高,通过DataTable循环或更多数据库调用?


下一篇:MySQL-根据列值插入多行