Smarty-内建函数(利用foreach、section遍历数组)

来源:互联网 发布:yy视听软件下载 编辑:程序博客网 时间:2024/05/16 10:12

Smarty—利用foreach、section遍历数组

一、利用foreach遍历数组
1.语法
<{foreach}>语句
<{foreachelse}>语句2
<{/foreach}>
2.foreach的四个属性:

from(待循环数组的名称)item(当前

处理元素的变量名称) key(当前处理元素的键名) name(该循环

的名称,用于访问该循环)
3.实例:
smarty.php文件

<?php

$array=array(array("id"=>"1","name"=>"张三","age"=>19),

array("id"=>"2","name"=>"李四","age"=>20),

array("id"=>"3","name"=>"王五","age"=>21));

include("libs/Smarty.class.php");//引入类
$smarty = new Smarty();//创建类
$smarty->template_dir="demo/templates";//更新模版存放路

径及编译路径
$smarty->compile_dir="demo/templates_c";//更新编译路径
$smarty->left_delimiter="<{";//修改界定符
$smarty->right_delimiter="}>";
$smarty->assign("array",$array);
$smarty->display(smarty.tpl);

?>

smarty.tpl文件

1.以表格的形式输出李四的信息
<table boder="1">
<caption><{$array[1].name}></caption>
<tr>
<{foreach from=$array[1] item=value}>
<td><{$array[1]}></td>
<{/foreach}>
</tr>
</table>
2.以表格的形式输出所有人的信息
<table boder="1">
<caption>学生信息表</caption>
<tr>
<{foreach from=$array item=row}>
<tr>
<{foreach from=$row item=value}>
<td><{$value}></td>
<{/foreach}>
</tr>
<{/foreach}>
</tr>
</table>
二、利用section遍历数组
1.语法
<{section}>
<{/section}>

2.section循环的六个属性:

 name(该循环的名称) loop(决定循环次数的变量名称) start(循环执行的初始位置)

step(该值决定循环的步长) max(决定循环最大执行次数) show(决定是否显示该循环)
3.实例
smarty.php文件

<?php

$array=array(array(1,"张三","age"=>19),array(2,"李四",20),array("3","王五",21));

include("libs/Smarty.class.php");//引入类
$smarty = new Smarty();//创建类
$smarty->template_dir="demo/templates";//更新模版存放路

径及编译路径
$smarty->compile_dir="demo/templates_c";//更新编译路径
$smarty->left_delimiter="<{";//修改界定符
$smarty->right_delimiter="}>";
$smarty->assign("array",$array);
$smarty->display(smarty.tpl);

?>

smarty.tpl文件

1.以表格的形式输出李四的信息 注意:section不能遍历关联数组
<table border="1">
<tr>
<{section name=array loop=$array[1]}>
<td><{$array[1][array]}></td>
<{/section}>
</tr>
</table>

2.以表格的形式输出所有人的信息
<table border="1">
<section name=row loop=$array>
<tr>
<section name=col loop=$array[row]>
<{/section}>
<td><{$array[row][col]}></td>
</tr>
<{/section}>
</table>

 

 

 

 

 


 

原创粉丝点击