功能:主要实现对数组的遍历输出
基本语法:
foreach,foreachelse
{foreach from=数组 key=键 name=名称 item=内容 }
{foreachelse}
{/foreach}
from:要遍历输出的数组
item:每次遍历时,系统会自动将遍历的结果放入item内容中
key:键值,每次遍历时,系统会将遍历的键值放入key中
name:foreach名称,为foreach起名
foreachelse:当数组为空时,执行此句
demo4.html示例代码
<!DOCTYPE html> <html> <head> <meta charset=’utf-8′> <title></title> </head> <body> {*一维数组*} {foreach from=$lamp item=’val’} {$val}<hr/> {/foreach} {*二维数组*} {foreach from=$persons item=’row’} {$row[‘name’]}–{$row[‘age’]}–{$row[‘sex’]} <hr/> {/foreach} {*其他参数的使用*} {foreach from=$lamp item=’val’ key=’k’} {$k}:{$val}<hr/> {/foreach} {*附加属性*} {foreach from=$persons item=’row’ name=’ps’} {$smarty.foreach.ps.index}:{$smarty.foreach.ps.iteration}:{[email protected]}:{[email protected]} {$row[‘name’]}-{$row[‘age’]}-{$row[‘sex’]}<HR/> {/foreach} 单前总共有{$smarty.foreach.ps.total}条记录 </body> </html>
demo4.php代码示例
<?php require “smarty/Smarty.class.php”; $smarty = new Smarty(); $lamp = array(‘php’,’mysql’,’apache’,’linux’); $persons = array( array(‘name’=>’lisi’,’age’=>’22’,’sex’=>’nan’), array(‘name’=>’zhangsam’,’age’=>’33’,’sex’=>’nv’), array(‘name’=>’wangwu’,’age’=>’44’,’sex’=>’yao’), array(‘name’=>’jj’,’age’=>’16’,’sex’=>’nan’) ); $smarty -> assign(‘lamp’,$lamp); $smarty -> assign(‘persons’,$persons); $smarty -> display(“demo4.html”);
例4:foreach附加属性
$smarty.foreach.name.index @index :循环索引(默认从0开始)
$smarty.foreach.name.iteration @iteration :循环迭代(当前是第几次循环)
$smarty.foreach.name.first @first :当第一次循环时,此值为true
$smarty.foreach.name.last @last :当最后一次循环时,此值为true
$smarty.foreach.name.total @total :统计当前循环次数
{*附加属性*} {foreach from=$persons item=’row’ name=’ps’} {$smarty.foreach.ps.index}:{$smarty.foreach.ps.iteration}:{[email protected]}:{[email protected]} {$row[‘name’]}-{$row[‘age’]}-{$row[‘sex’]}<HR/> {/foreach} 单前总共有{$smarty.foreach.ps.total}条记录
示例代码:
时间: 2024-12-19 10:54:52