2014-12-05 195 views
0

我想回到foreach语句中,如下面的示例代码所示。 有没有办法做到这一点?嵌套html与PHP 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> 
+0

我想再次以相同的顺序打印出相同的东西。不确定插值是什么意思。 – aahhaa 2014-12-05 04:05:55

+0

难道你只是再次运行循环? (在你需要的下一节中有另一个'foreach'循环吗?) – Darren 2014-12-05 04:06:39

+0

将foreach结果保存到一个变量中,然后在你想要的地方打印变量? – Prix 2014-12-05 04:06:55

回答

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

+0

我喜欢功能想法谢谢。我想我只是没有真正想过。 – aahhaa 2014-12-05 04:11:55

+0

@wlin干杯!确保你接受你认为最能解决你的问题的答案。 – sjagr 2014-12-05 04:17:08

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

?> 

据我所知,外面

<?php ?> 

标签每个HTML代码将被视为回声 “HTML代码” 当PHP intepreter读取PHP文件。