在 PHP 中 Foreach 中断并继续

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16654448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:30:45  来源:igfitidea点击:

Foreach break and continue in PHP

phpforeachbreak

提问by user1629905

I am facing an problem. I have built a foreachloop in PHP:

我正面临一个问题。我foreach在 PHP 中构建了一个循环:

 <?php $show = false; ?>
 <?php foreach ($this->items as $item) : ?>

But I want to echo the first 20 items and continue with the following 16 items.

但我想回应前 20 项并继续以下 16 项。

I have managed to make it to do a break after 20 items but I am not getting the following 16 items ( starting from nr 21 ).

我设法在 20 个项目后休息一下,但我没有得到以下 16 个项目(从 nr 21 开始)。

This is what I have so far:

这是我到目前为止:

<?php $show = false; ?>
<?php $i = $item->id = 1; ?>
<?php foreach ($this->items as $item) : ?>
<?php if(++$i > 20) break; ?>

If I set $ito '21'it still echos item 1 and so on.

如果我设置$i'21'它仍然回显项目 1 等等。

Solution ## Thanks to @dhavald

解决方案## 感谢@dhavald

<?php $show = false; ?>                                   
<?php foreach (array_slice ($this->items, 0, 20) as $item) : ?>

By placing an array_slicein the foreach you can control the items you want show. So on the next div i want to show item 21 to 36, the only thing i had to change was the 0 and 20 into , 20, 36

通过array_slice在 foreach 中放置,您可以控制要显示的项目。所以在下一个 div 我想显示项目 21 到 36,我唯一需要改变的是 0 和 20 到 , 20, 36

To clarify what I am looking for, I have three divs where I want to echo some items onto it. If an user collapse a div on the first there will appear the first 20 items and if a user clicks div2 the next 16 items will appear.

为了澄清我在寻找什么,我有三个 div,我想在其中回显一些项目。如果用户在第一个折叠 div 将出现前 20 个项目,如果用户单击 div2 将出现接下来的 16 个项目。

How can I correct this code to make that happen?

我该如何更正此代码以实现这一目标?

As i forgotten to mention, the solutions you bring on helped me really to understand the process but as i used a component generator for Joomla 3.1 there is one row of code that make it a little bit more complex to call the first 20 and second 16 items.

正如我忘记提到的,您带来的解决方案帮助我真正理解了这个过程,但是当我使用 Joomla 3.1 的组件生成器时,有一行代码使得调用第一个 20 和第二个 16 变得有点复杂项目。

Directly after the foreach loop there is this line of code

在 foreach 循环之后直接有这行代码

if($item->state == 1 || ($item->state == 0 && JFactory::getUser()>authorise('core.edit.own',' com_ncitycatemus.vraagantwoordtoevoegen.'.$item->id))):

$show = true;

How can i manage it than with the loop ? Or do you suggest another way?

我怎样才能管理它而不是循环?或者你有其他建议吗?

Thanks in advance! Really helped me to understand the loop!!

提前致谢!真的帮助我理解循环!!

回答by h2ooooooo

breakbreaks out of and stops a loop. continueskips the rest of the code in the loop, and jumps to the next iteration.

break跳出并停止循环。continue跳过循环中的其余代码,并跳转到下一次迭代。

Using breakand continueis in my opinion the wrong approach here. I'd simply use two for loops:

在我看来,使用breakandcontinue是错误的方法。我只是使用两个 for 循环:

$keys = array_keys($this->items);
$keysLength = count($keys);

echo '<div id="div1">';
for ($i = 0; $i < min($keysLength, 20); $i++) {
    echo $this->items[$keys[$i]];
}
echo '</div>';

if ($keysLength >= 20) {
    echo '<div id="div2">';
    for ($i = 20; $i < min($keysLength, 36); $i++) { //36 being 20 + 16
        echo $this->items[$keys[$i]];
    }
    echo '</div>';
}

Note: This will work with any amount of items in $this->items. If it's under 20, it'll simply skip the next 16, and if it's above 36, it'll simply ignore the rest.

注意:这将适用于$this->items. 如果它低于 20,它会简单地跳过接下来的 16,如果它高于 36,它会简单地忽略其余的。

回答by Chen Kinnrot

Don't use break; use continue;

不要使用中断;使用继续;

回答by dhavald

you can use array_sliceto get a part of $this->items array and assign it into 3 different variables and loop over them separately.

您可以使用array_slice获取 $this->items 数组的一部分并将其分配给 3 个不同的变量并分别循环遍历它们。

$itemsDiv1 = array_slice($this->items, 0, 20);  // gives first 20 items
$itemsDiv2 = array_slice($this->items, 20, 16); // gives next 16 items

and so on..

等等..

回答by philippinedev

<?php $i = 0; ?> 

<!-- first group -->
<div>

<?php foreach ($this->items as $item) : ?> 
<?php
/**
 * Check if count divided by 20 has no remainder
 */
if ( (++$i % 20) == 0 ): ?>

</div>
<!-- start new group -->
<div>

<?php endif ?>
<?php endforeach ?>

<!-- end last group -->
</div>

回答by adyopo

$stockNotNull = StockDetail::where('sku', 10101001)
            ->where('stock_quantity', '>', 0)->get('stock_id', 'stock_quantity');
        $toSell = 14;
        // decrements just once for each $stockNotNull
        foreach ($stockNotNull as $product) {
            if ($toSell < 1) {
                return;
            }
            $product->decrement('stock_quantity');
//            $product->stock_quantity--; returns with a null
//            dump($product->stock_quantity);
            $product->save();
            $toSell--;
//            dump($toSell);
            if($product->stock_quantity === 0) {
                continue;
            }
        }

This is what I got so far, decrementing in the usual manner i.e $variable-- gives me a null value, $product->decrement('stock_quantity') subtracts 1 on each run, even if the stock_quantity field is far greater than the $toSell variable. The logic is there in my head, I'm just having trouble taking the quantity from the current item and moving on to the next only when the stock_quantity is 0.

这是我到目前为止得到的,以通常的方式递减,即 $variable-- 给我一个空值,$product->decrement('stock_quantity') 在每次运行时减去 1,即使 stock_quantity 字段远大于$toSell 变量。逻辑就在我的脑海中,我只是在从当前项目中获取数量并仅在 stock_quantity 为 0 时才移动到下一个项目时遇到问题。