【问题标题】:nesting html with php foreach statement用 php foreach 语句嵌套 html
【发布时间】:2014-12-05 04:02:45
【问题描述】:

我正在尝试回到 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>

【问题讨论】:

  • 我想以同样的顺序再次打印出同样的东西。不太确定插值是什么意思。
  • 你不会再次运行循环吗? (在下一部分中还有另一个foreach 循环吗?)
  • 将 foreach 结果保存到变量中,然后在您想要的位置打印变量?

标签: php html loops foreach


【解决方案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; 任意数量。经销商的选择!

【讨论】:

  • 我喜欢这个函数的想法,谢谢。我想我只是没有真正考虑清楚。
  • @wlin 干杯!确保您接受您认为最能解决您的问题的答案。
【解决方案2】:

如果您的意思是 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 文件时,标签将被视为 echo "html code"。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2017-01-13
    • 2018-10-07
    相关资源
    最近更新 更多