繁体   English   中英

用php foreach语句嵌套html

[英]nesting html with php foreach statement

我正尝试重新进入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>

我想再次以相同的顺序打印相同的东西

通过这种逻辑,您可以定义一个函数:

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
    }
}

然后,在您希望使该foreach循环再次发生的任何时候使用outputBoxes($boxes)

@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; 我们想要的。 经销商的选择!

如果您的意思是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 ?>

当PHP解释器读取PHP文件时,标记将被视为回显“ html代码”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM