数组过滤器限制PHP结果的数量

时间:2016-08-08 11:53:33

标签: php arrays

我有以下方法

public function getNextAvailableHousesToAttack(\DeadStreet\ValueObject\House\Collection $collection, $hordeSize)
{
    $houses = $collection->getHouses();

    $housesThatCanBeAttacked = array_filter($houses, function($house) use (&$hordeSize) {
        if(!isset($house)) {
            return false;
        }
        $house = $this->houseModel->applyMaxAttackCapacity($house, $hordeSize);
        if($this->houseModel->isAttackable($house)) {
            return $house;
        }
        return false;
    });

    return $housesThatCanBeAttacked;

但是,此数组可以是 huge

我希望将$housesThatCanBeAttacked限制为$hordeSize所设置的大小,因为我只需要和部落中的僵尸一样多的房子来攻击这一轮。

然而,这个阵列$housesThatCanBeAttacked最终可能包含100万个房屋,僵尸部落中只有100个。

有没有办法限制从回调构建的这个数组的大小?

2 个答案:

答案 0 :(得分:1)

你可以简单地使用一个循环,并在有足够的房屋时停止处理数组。

$houses = $collection->getHouses();
housesThatCanBeAttacked[];
$i = 0;

foreach ($houses as $house) {
    $house = $this->houseModel->applyMaxAttackCapacity($house, $hordeSize);
    if ($this->houseModel->isAttackable($house)) {
        housesThatCanBeAttacked[] = $house;
        if (++$i == $hordeSize) {
            break;
        }
    }
}

答案 1 :(得分:0)

我会在回调之外添加一个房屋柜台,并在回调中使用它来跳过所有过多的房屋。以下是解决方案的外观:

public function getNextAvailableHousesToAttack(\DeadStreet\ValueObject\House\Collection $collection, $hordeSize)
{
    $houses = $collection->getHouses();
    $counter = $hordeSize;

    $housesThatCanBeAttacked = array_filter($houses, function($house) use (&$hordeSize, &$counter) {
        if($counter == 0 && !isset($house)) {
            return false;
        }
        $house = $this->houseModel->applyMaxAttackCapacity($house, $hordeSize);
        if($this->houseModel->isAttackable($house)) {
            $counter--;
            return $house;
        }
        return false;
    });

    return $housesThatCanBeAttacked;

这样您array_filter就不会再返回$counter以上的值。