foreach 循环不限于预期的计数器

foreach loop not limited to counter as expected

我正在通过 cURL 方法接收数据,tat 'feed' ($data) 包含八个帖子 ($post) 顶部。我需要对这个 feed (if (!$postTypeExcl)) 应用一些条件逻辑,我只想输出总共四个帖子。我尝试了以下块,但这不起作用。输出所有帖子,但仅限于 if (!$postTypeExcl)。所以唯一不起作用的是计数器。

我特意将计数器放在 foreach 循环之外,这样即使计数器达到最大值,引擎也不会继续循环。

$counter = 0;
if ($counter < 4) {
    foreach ($data as $post) {
        $postTypeExcl = $post->getProperty('story');
        if (!$postTypeExcl) {
            // Output some HTML

            $counter++;
        }
    }
}

这是您的代码:

$counter = 0;
if ($counter < 4) {
    // .. do something ...
}

0 总是小于 4,所以 "do something" 发生了。那就是你的循环了。

你要找的是break,退出循环:

foreach ($data as $post) {
    $postTypeExcl = $post->getProperty('story');
    if (!$postTypeExcl) {
        // Output some HTML

        $counter++;
    }
    if ($counter > 4) break;
}

为什么你的 if 语句在循环之外?

$counter = 0;

    foreach ($data as $post) {
        if ($counter >=4) break;
        $postTypeExcl = $post->getProperty('story');
        if (!$postTypeExcl) {
            // Output some HTML

            $counter++;
        }
    }

类似的东西。