使用php foreach语句嵌套html

时间:2014-12-05 04:02:45

标签: php html loops foreach

我正在尝试回到foreach语句,如下面的示例代码所示。 有没有办法做到这一点?

<?php 
    foreach($boxes as $box) 
    {
       foreach($box as $thing) 
       {
?>
        <img src="<?php echo $thing ?>"/>
<?php
       }  
    }
?>

<!-- more html code here outside of foreach statement that don't want to be loop -->

// want to go back in to the foreach statement     

<?php echo $thing; ?>

所以输出将是

<img src="1">
<img src="2">
<img src="3">

<div>this only appear once</div>

<img src="1"><p>1</p>
<img src="2"><p>2</p>
<img src="3"><p>3</p>

2 个答案:

答案 0 :(得分:1)

  

I want to print out the same thing in the same order again

根据这个逻辑,你可以定义一个函数:

function outputBoxes($boxes) {
    foreach($boxes as $box) {
        foreach($box as $thing) { // you can make the next two lines valid with ?>
            <!-- html code here -->
            <img src="<?php echo $thing ?>"/>
        <?php } // and now we're back in PHP
    }
}

然后随时使用outputBoxes($boxes),以便再次发生foreach循环。

@Prix也带来了一个有效的参数,因为我们希望避免作为程序员的无聊循环:

function outputBoxes($boxes) {
    $out = '';
    foreach ($boxes as $box) {
        foreach ($box as $thing) {
            $out .= '<!-- html code here -->' .
                    '<img src=' . $thing . ' />';
        }
    }
    return $out;
}

然后,您可以根据需要echo outputBoxes($boxes);$boxHtml = outputBoxes($boxes);,只需echo $boxHtml;。经销商的选择!

答案 1 :(得分:0)

如果你的意思是foreach将打印html代码n次,只需将大括号放在html代码下。但是你有2个foreach,所以我不知道哪一个。我只是将两个近距离放下。

    <?php 
        foreach($boxes as $box) {
                  foreach($box as $thing) {
                        <!-- html code here -->
                        <img src='<?php echo $thing ?>'/>
    ?>

    <!-- more html code here outside of foreach statement that don't want to be loop -->

    // want to go back in to the foreach statement     

    <?php 
echo $thing;
                  }  
        }

?>

据我所知,每个html代码都在

之外
<?php ?>

标记将被视为echo&#34; html代码&#34;当PHP解释器读取PHP文件时。