本文實例講述了smarty內置函數foreach用法。分享給大家供大家參考。具體如下:
輸出文件:index.php
復制代碼 代碼如下:<?php
require_once('libs/Smarty.class.php');
$smarty = new Smarty();
$smarty->setTemplateDir($_SERVER['DOCUMENT_ROOT']."/php/templates/");
$smarty->setCompileDir($_SERVER['DOCUMENT_ROOT']."/php/templates_c/");
$smarty->setCacheDir($_SERVER['DOCUMENT_ROOT']."/php/cache/");
$smarty->caching = false;
$name = array("喜洋洋","美洋洋","懶洋洋","哈哈哈");
$family = array("husband"=>"喜洋洋","wife"=>"美洋洋","boy"=>"懶洋洋","girl"=>"哈哈哈");
$smarty->assign("name",$name);
$smarty->assign("family",$family);
$smarty->display("temp.htm");
?>
模板文件:temp.htm
復制代碼 代碼如下:{foreach $name as $value}
{$value}
{/foreach}
<hr />
{foreach $family as $family_name}
{$family_name@key} = {$family_name}
{/foreach}
<br />
{foreach from=$family item=f_name key=k}
{$k} = {$f_name}
{/foreach}
<hr />
數組的輸出方法大致有兩種形式:
(1)一種是smarty 2的 {foreach from=數組變量名 item=數組值}。
(2)smarty 3的輸出方法與php的一致,上面實例沒有加$key,需要輸出鍵名時,采用實例裡的形式 @key;你可以使用$key=>$value這種形式。
另外,如果只取數組中某一個值,可以直接輸出,如關聯數組的 {$family.husband}、索引數組的 {$name[0]}等。
希望本文所述對大家的php程序設計有所幫助。