过滤 PHP 数组是否会导致数字跳过


Does filtering a PHP array cause numbers to skip?

我有以文章列表开头的代码。 我只想保留那些附加了缩略图的缩略图,所以我编写了函数findThumb尝试获取图像,或者在出错时返回 false。 一切正常,但是当输出显示在编号列表中时,计数完全跳过数字8和9(即5,6,7,10)。 我不知道为什么 - 当它计数时,它已经在使用过滤列表。 我对PHP很陌生,所以我想知道这是否是我不知道的一些奇怪的语言怪癖。

<?php
$popularArticles = $curatedArticles->fetchGroup('most-popular');
$findThumb = function ($article) {
    try{
        return $article->original->getImageUrl('tiny');
    } catch (Exception $e) {
        return false;
    }
};
$popularArticlesWithImages = array_filter($popularArticles, $findThumb);
<section>
<?
    $totalArticles = 10;
    foreach($popularArticlesWithImages as $i => $popularArticle):
        if ($i >= $totalArticles){ break; }
?>
    <dl>
        <dt><?= $i + 1 ?></dt>
        <dd class="most-popular-title"><?= $popularArticle->title ?></dd>
        <? endforeach ?>
    </dl>
</section>

根据 PHP 文档:

循环访问数组中的每个值,将它们传递给回调函数。如果回调函数返回 true,则数组中的当前值将返回到结果数组中。保留数组键。

(我的强调)

如果你不想保留键,那么只需对过滤后的数组运行 array_values()

$popularArticlesWithImages = array_values(array_filter($popularArticles, $findThumb));