过滤PHP数组会导致数字跳过吗?

时间:2015-01-15 19:44:05

标签: php

我的代码以文章列表开头。我只想保留附有缩略图的那些,所以我编写了函数findThumb来尝试获取图像,或者如果它发生错误则返回false。一切正常,但当输出显示在编号列表中时,计数完全跳过数字8和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>

1 个答案:

答案 0 :(得分:2)

根据PHP documentation

  

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

(我的重点)

如果您不想保留密钥,只需针对已过滤的数组运行array_values()

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