foreach内置函数:
语法格式如下:
1、{foreach $arrayvar as $itemvar}
2、{foreach $arrayvar as $keyvar=>$itemvar}
{foreach}还有一些属性,非常有用,有以下6个
1、@index , 当前数组索引,从0开始计算
2、@iteration,当前循环的次数,从1开始计算
3、@first,首次循环时,该值为true
4、@last,循环到最后一次时,该值为true
5、@total,总的循环次数,可在foreach内部使用,也可以在循环完成之后使用
6、@show,在foreach循环执行完之后,检测循环是否显示数据的判断
注意细节
1、还带一个 {foreachelse}的分支,当$arr中没有内容时会执行
2、smarty 2之前的写法 {foreach from = $arr key = "key" item="value"} 也是可以支持的
foreach.php(后端):
<?php
include "libs/Smarty.class.php";
$smarty = new Smarty();
$smarty->template_dir = "templates";
$smarty->compile_dir = "templates_c";
//分配数据
//数组的分配
$user = array('张无忌','李寻欢','王语嫣','赵敏');
$smarty->assign('user',$user);
$hero = array('id'=>1,'name'=>'黄药师','nickname'=>'东邪');
//二维数组
$heros = array(
array('id'=>1,'name'=>'黄药师','nickname'=>'东邪','weapon'=>'萧'),
array('id'=>2,'name'=>'欧阳锋','nickname'=>'西毒','weapon'=>'蛇'),
array('id'=>3,'name'=>'一灯大师','nickname'=>'南帝','weapon'=>'手指'),
array('id'=>4,'name'=>'洪七公','nickname'=>'北丐','weapon'=>'打狗棒'),
array('id'=>5,'name'=>'王重阳','nickname'=>'中神通','weapon'=>'浮尘')
);
$smarty->assign('hero',$hero);
$smarty->assign('heros',$heros);
$smarty->display("foreach.tpl");
foreach.tpl(前端视图):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
{literal}
.odd{background: #ddd;}
{/literal}
</style>
</head>
<body>
<h1>foreach函数的使用</h1>
<h2>一维数组</h2>
<ul>
{foreach $user as $k => $v}
<li>{$k}---{$v}</li>
{/foreach} {* foreach一定要有结束 *}
</ul>
<br>
<ul>
{foreach $hero as $k => $v}
<li>{$k}---{$v}</li>
{/foreach}
</ul>
<h2>二维数组</h2>
<table width="600" border="1">
<tr><th>编号</th><th>姓名</th><th>绰号</th><th>武器</th></tr>
{foreach $heros as $v}
<tr>
{foreach $v as $v1}
<td>{$v1}</td>
{/foreach}
</tr>
{/foreach}
</table>
<br>
<table width="600" border="1">
<tr><th>编号</th><th>姓名</th><th>绰号</th><th>武器</th></tr>
{foreach $heros as $v}
<tr {if $v@first} class='first' {/if} > {* $v@first:如果$v是第一个元素。 foreach结合if完成复杂的功能 *}
<td>{$v.id}</td>
<td>{$v.name}</td>
<td>{$v.nickname}</td>
<td>{$v['weapon']}</td>
</tr>
{/foreach}
</table>
{* 隔行换色 *}
<table width="600" border="1">
<tr><th>编号</th><th>姓名</th><th>绰号</th><th>武器</th></tr>
{foreach $heros as $v}
<tr class = "{if $v@iteration is odd}odd{else}even{/if}" > {* @iteration表示循环次数,从1开始,@index索引从0开始 *}
<td>{$v.id}</td>
<td>{$v.name}</td>
<td>{$v.nickname}</td>
<td>{$v['weapon']}</td>
</tr>
{/foreach}
</table>
</body>
</html>