1. foreach:用于循环简单数组,它是一个选择性的section循环,它的定义格式为:
===========================================
{foreach from=$array item=array_id}
{foreachelse}
{/foreach}
其中,from 指出要循环的数组变量,item为要循环的变量名称,循环次数由from所指定的数组变量的个数所决定。{foreachelse}用来当程序中传递过来的数组为空时的处理,下面是一个简单的例子:
example6.tpl
===========================================
<html>
<head><title>这是一个foreach使用的例子</title></head>
<body>
这里将输出一个数组:<br>
<{foreach from=$newsArray item=newsID}>
新闻编号:<{$newsID.newsID}><br>
新闻内容:<{$newsID.newsTitle}><br><hr>
<{foreachelse}>
对不起,数据库中没有新闻输出!
<{/foreach}>
</body>
</html>
example6.php
==========================================
<?php
/*********************************************
*
* 文件名: example6.php
* 作 用: 显示实例程序2
*
* 作 者: 大师兄
* Email:
teacherli@163.com
* 修 正: forest
*********************************************/
include_once("./comm/Smarty.class.php");
$smarty = new Smarty();
$smarty->templates("./templates");
$smarty->templates_c("./templates_c");
$smarty->cache("./cache");
$smarty->cache_lifetime = 0;
$smarty->caching = true;
$smarty->left_delimiter = "<{";
$smarty->right_delimiter = "}>";
$array[] = array("newsID"=>1, "newsTitle"=>"第1条新闻");
$array[] = array("newsID"=>2, "newsTitle"=>"第2条新闻");
$array[] = array("newsID"=>3, "newsTitle"=>"第3条新闻");
$array[] = array("newsID"=>4, "newsTitle"=>"第4条新闻");
$array[] = array("newsID"=>5, "newsTitle"=>"第5条新闻");
$array[] = array("newsID"=>6, "newsTitle"=>"第6条新闻");
$smarty->assign("newsArray", $array);
//编译并显示位于./templates下的index.tpl模板
$smarty->display("example6.tpl");
?>
=================================================
example6.php 输出文件
=================================================
<html>
<head><title>foreach使用的例子</title></head>
<body>
这里将输出一个数组:<br>
新闻编号:1<br>
新闻内容:第1条新闻<br><hr>
新闻编号:2<br>
新闻内容:第2条新闻<br><hr>
新闻编号:3<br>
新闻内容:第3条新闻<br><hr>
新闻编号:4<br>
新闻内容:第4条新闻<br><hr>
新闻编号:5<br>
新闻内容:第5条新闻<br><hr>
新闻编号:6<br>
新闻内容:第6条新闻<br><hr>
</body>
</html>
foreach还可以用foreachelse来匹配,用foreachelse来表示当传递给foreach的数组为空值时程序要执行的操作,具体的使用方法,请参考手册的说明。