foreach循环使用
时间:2008-07-23 来源:mars531706
PHP
/linuxman 发表于2007-03-01, 22:02
使用foreach控制smarty中的循环很方便,但是需要注意以下几个方面:
1
item="variable_name"中的variable_name是变量的名字,因此不需要在variable_name前面使用$符号。比如
{foreach item="article " from=$articles}{/foreach}
这个循环中,article是每次循环得到的变量名字,在循环体中可以通过$article来使用这个变量。
2 还是上面这个例子,item="article"部分,要注意到article需要用双引号括起来,这样比较符合W3C的xhtml规范。
3 最为重要的,是要透彻理解from后面声明的变量,在上面的例子中就是$articles,是一个任意类型的集合对象。这个问题下面重点 说以下。
假设$articles可以是简单的字符串数组,比如:$articles={'ab','cd','dd'},则这个例子可以这样写:
{foreach item="article" from=$articles}
{$article}
{/foreach}
将输出:
ab
cd
dd
又假设$articles是一个比较复杂的数组,其中的每一个元素都是一个article类型的对象,可以通过$article->getTopic获得文章的标题等,则可以有如下的代码:
{foreach item="article" from=$articles}
{$article->getTopic}
{$article->getContent}
{/foreach}
上面的代码将输出每一篇文章的标题和内容。
因此,foreach循环中经常如上使用复杂对象。
相关阅读 更多 +