简体   繁体   English

数组过滤器限制结果数PHP

[英]Array Filter limit amount of results PHP

I have the following method 我有以下方法

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;

However, this array can be huge . 但是,此数组可能很大

I want to limit $housesThatCanBeAttacked to whatever the size of $hordeSize is set to, as I only need as many houses as there are zombies in the horde to attack this round. 我想限制$housesThatCanBeAttacked到任何大小$hordeSize设置为,因为我只因为有在部落进攻这一轮的僵尸需要尽可能多的房子。

However, this array $housesThatCanBeAttacked could end up containing 1 million houses, where there are only 100 in the zombie horde. 但是,这个$housesThatCanBeAttacked数组$housesThatCanBeAttacked可能包含100万所房屋,而僵尸部落中只有100所房屋。

Is there a way to limit the size of this array built from the callback? 有没有办法限制通过回调构建的此数组的大小?

You could simply use a loop, and stop processing the array when you have enough houses. 您可以简单地使用循环,并在有足够的房子时停止处理数组。

$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;
        }
    }
}

I would add a counter of houses outside of callback and use it inside callback to skip all excessive houses. 我会在回调外添加房屋计数器,并在回调内使用它来跳过所有多余的房屋。 Here is how a solution can look like: 解决方案如下所示:

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;

This way you array_filter won't return more then $counter values. 这样,您的array_filter不会返回更多的$counter值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM