本文实例讲述了smarty内建函数foreach的使用方法,分享给大家供大家参考。具体如下:
代码如下:
PHP
//创建smarty对象
require_once("./libs/Smarty.class.PHP");
$smarty = new Smarty();
$arr1 = array("北京","上海","广州");//索引数组 $smarty->assign("arr1",$arr1);//分配索引数组 $arr2 = array("city1"=>"北京","city2"=>"上海","city3"=>"广州");//关联数组 $smarty->assign("arr2",$arr2);//分配关联数组 $arr3 = array(array("北京","广州"),array("关羽","张飞","美女"));//二维索引数组 $smarty->assign("arr3",$arr3); $arr4 = array(array("c1"=>"北京","c2"=>"上海","c3"=>"广州"),array("n1"=>"关羽","n2"=>"张飞","n3"=>"美女"));//二维关联数组 $smarty->assign("arr4",$arr4);
$smarty->display("temp.tpl"); ?>
模板文件:temp.tpl
代码如下:
smarty内建函数foreach,循环取出数组值
{foreach from=$arr1 item=temp} {$temp} {/foreach}
item为键值,key为键名。如果不取key,取出方法与一维索引数组相同,当然索引数组也是有key的0,1,2...
{foreach from=$arr2 item=temp key=k} {$k}={$temp} {/foreach}两次循环即可
{foreach from=$arr3 item=temp} {foreach from=$temp item=value} {$value} {/foreach}{/foreach}
同样两次循环即可
{foreach from=$arr4 item=temp} {foreach from=$temp item=value key=k} {$k}={$value} {/foreach}{/foreach}