Home >Backend Development >PHP Tutorial >smarty内置函数foreach用法实例_PHP

smarty内置函数foreach用法实例_PHP

WBOY
WBOYOriginal
2016-05-31 13:17:14938browse

本文实例讲述了smarty内置函数foreach用法。分享给大家供大家参考。具体如下:

输出文件:index.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}



{foreach $family as $family_name}
{$family_name@key} = {$family_name}
{/foreach}


{foreach from=$family item=f_name key=k}
{$k} = {$f_name}
{/foreach}

数组的输出方法大致有两种形式:

(1)一种是smarty 2的 {foreach from=数组变量名 item=数组值}。
(2)smarty 3的输出方法与php的一致,上面实例没有加$key,需要输出键名时,采用实例里的形式 @key;你可以使用$key=>$value这种形式。

另外,如果只取数组中某一个值,可以直接输出,如关联数组的 {$family.husband}、索引数组的 {$name[0]}等。

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn