我正试图回到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>发布于 2014-12-05 04:07:30
根据这种逻辑,您可以定义一个函数:
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;,就像我们想要的那样。毒贩的选择!
发布于 2014-12-05 04:08:12
如果您的意思是foreach将打印html代码n次,只需将curly括号放在html代码下即可。但你有两个前程所以我不知道是哪一个。我就把这两个近括号都放下。
<?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代码“。
https://stackoverflow.com/questions/27308557
复制相似问题