本文實例講述了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程序設計有所幫助。