本文实例讲述了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程序设计有所帮助。