本文实例讲述了smarty内建函数foreach的使用方法,分享给大家供大家参考。具体如下:
显示文件:index.php:
<?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
<html> <h2>smarty内建函数foreach,循环取出数组值</h2> <p style="color:green">实例1:一维索引数组</p> {foreach from=$arr1 item=temp} {$temp} {/foreach}<p style="color:orange">实例2:一维关联数组——>item为键值,key为键名。如果不取key,取出方法与一维索引数组相同,当然索引数组也是有key的0,1,2...</p> {foreach from=$arr2 item=temp key=k} {$k}={$temp} {/foreach}
<p style="color:red">实例3:二维索引数组——>两次循环即可</p> {foreach from=$arr3 item=temp} {foreach from=$temp item=value} {$value} {/foreach}<br /> {/foreach}
<p style="color:red">实例4:二维关联数组——>同样两次循环即可</p> {foreach from=$arr4 item=temp} {foreach from=$temp item=value key=k} {$k}={$value} {/foreach}<br /> {/foreach}
</html>
希望本文所述对大家的php程序设计有所帮助。