endforeach在循环? [英] endforeach in loops?
问题描述
这是主要的,因此您可以在循环中创建HTML时使开始和结束语句更清晰:
< table>
<? while($ record = mysql_fetch_assoc($ rs)):?>
<? if(!$ record ['deleted']):?>
< tr>
<? foreach($ display_fields as $ field):?>
< td><?= $ record [$ field]?>< / td>
<? endforeach; ?>
< td>
<? foreach($ action为$ action):?>
< option value =<?= $ action?>><?= $ action?>
<? endforeach; ?>
< / td>
< / tr>
<?其他:?>
< tr>< td colspan =<?= array_count($ display_fields)?>>< i>记录<?= $ record ['id']?>已被删除< / i>< / td>< / tr>
<?万一; ?>
<? ENDWHILE; ?>
< / table>
<表>
<? while($ record = mysql_fetch_assoc($ rs)){?>
<? if(!$ record ['deleted']){?>
< tr>
<? foreach($ display_fields as $ field){?>
< td><?= $ record [$ field]?>< / td>
<? }?>
< td>
<? foreach($ action为$ action){?>
< option value =<?= $ action?>><?= action?>
<? }?>
< / td>
< / tr>
<? } else {?>
< tr>< td colspan =<?= array_count($ display_fields)?>>< i>记录<?= $ record ['id']?>已被删除< / i>< / td>< / tr>
<? }?>
<? }?>
< / table>
希望我的例子足以证明一旦你有几层嵌套循环,并且缩进抛出所有的PHP开放/关闭标签和所含的HTML(也许你必须缩进的HTML一定的方式来让你的网页你想要的方式),备用语法( endforeach
)表单可以使您的大脑更容易解析。用正常的风格,结束}
可以自己留下来,并且很难说出它们实际上是关闭的。
I use brackets when using foreach loops. What is endforeach for?
It's mainly so you can make start and end statements clearer when creating HTML in loops:
<table>
<? while ($record = mysql_fetch_assoc($rs)): ?>
<? if (!$record['deleted']): ?>
<tr>
<? foreach ($display_fields as $field): ?>
<td><?= $record[$field] ?></td>
<? endforeach; ?>
<td>
<select name="action" onChange="submit">
<? foreach ($actions as $action): ?>
<option value="<?= $action ?>"><?= $action ?>
<? endforeach; ?>
</td>
</tr>
<? else: ?>
<tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
<? endif; ?>
<? endwhile; ?>
</table>
versus
<table>
<? while ($record = mysql_fetch_assoc($rs)) { ?>
<? if (!$record['deleted']) { ?>
<tr>
<? foreach ($display_fields as $field) { ?>
<td><?= $record[$field] ?></td>
<? } ?>
<td>
<select name="action" onChange="submit">
<? foreach ($actions as $action) { ?>
<option value="<?= $action ?>"><?= action ?>
<? } ?>
</td>
</tr>
<? } else { ?>
<tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
<? } ?>
<? } ?>
</table>
Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach
) form can make things easier for your brain to parse. With the normal style, the closing }
can be left on their own and make it hard to tell what they're actually closing.
这篇关于endforeach在循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!