PHP为foreach循环的一些但不是所有迭代添加值

时间:2016-11-29 15:04:58

标签: php arrays

初学者程序员在这里。

我在目录中有图片被推入数组

$pressImages = scandir('img/press');

然后切片以删除系统文件

$slice = array_slice($pressImages, 3);

然后通过循环将每个图像打印到网页上

foreach ($slice as $image) {
 echo "<div class='press list-item'><img src='img/press/$image' /></div>";
}

我想在循环的前四次迭代中添加锚标记(每个链接都是唯一的),但不是其他链接。我正在尝试学习如何将指令合并到尽可能少的数量。我需要在这里创建两个单独的循环吗?我想我会创建两个目录,一个用于具有链接的图像,另一个用于没有链接的图像,每个都有自己的foreach循环,但我的直觉表明可能有更有效的方式。

提前感谢您的帮助!

**一些精彩的建议大家再次感谢,学到了很多东西。我一直无法自己尝试这些,所以依靠可视化它们。我一定会尽快选择答案

4 个答案:

答案 0 :(得分:1)

<强>已更新

您可以像这样使用foreach键(请参阅Official PHP foreach docs):

foreach ($slice as $key => $image) {
    if($key > 3) {
        echo "<div class='press list-item'><img src='' /></div>";
    } else {
        echo "<a href='your_link_here'><div class='press list-item'><img src='img/press/$image' /></div></a>";
    }
}

希望这有帮助!

答案 1 :(得分:1)

您可以使用array_walk执行此“功能样式”:

array_walk($images, function ($image, $_, &$count) {
    $count += 1;

    $image = "<img src='img/press/$image'/>";

    if ($count <= 4) {
        $image = "<a href='#'>$image</a>";
    }

    echo "<div class='press list-item'>$image</div>", PHP_EOL;
}, 0);

您可以注意到我仅使用if而没有使用else。这是PHP(以及许多其他语言)的一个很好的实践。例如,你应该看看像PHP Mess Detector这样伟大的工具。有一个规则:

  

永远不需要带有else分支的if表达式。您可以   以不必要的方式重写条件   代码变得更容易阅读。要实现这一目的,尽早回归   声明。要实现这一点,您可能需要将代码分成几个   较小的方法。对于非常简单的作业,您也可以使用   三元运作。

这是一个working demo of my solution

PHP_EOL中的

echo仅用于结果显示。随意删除它。

另外,请注意,您不能总是依赖数组键作为计数器。在头部示例的顶部是当您需要对图像进行排序时,则索引将不按顺序排列。

此外:

如果您有两个阵列:$images$links,并且它们可以与外观顺序相关联,那么您可以使用array_map

array_map(function ($image, $link) {
    $image = "<img src='img/press/$image'/>";

    if ($link) {
        $image = "<a href='$link'>$image</a>";
    }

    // Or you can return string here and array_map will 
    // create an array of all resulting images.
    echo "<div class='press list-item'>$image</div>", PHP_EOL;
}, $images, $links);

使用array_map的原因是你可以提供多个数组并并行遍历它们。

这是working demo

答案 2 :(得分:0)

只需添加一个递增的计数器,然后使用if块:

$count = 0;
foreach ($slice as $image) {
    $count++;
    if($count <= 4){
        echo 'your link html here';
    }else{
        echo 'your non link html here';
    }
}

或略短:

$count = 4;
foreach ($slice as $image) {
    if($count--){
        echo 'your link html here';
        break;
    }
    echo 'your non link html here';
}

答案 3 :(得分:0)

链接每次都一样吗?

foreach ($slice as $count => $image) {
    if($count > 3){
        echo "<div class='press list-item'><a href='#'><img src='img/press/$image' /></a></div>";
    }else{
        echo "<div class='press list-item'><img src='img/press/$image' /></div>";
    }
}

如果我正确地回答你的问题,这对你有用。