smarty内置函数foreach用法实例,smartyforeach
本文实例讲述了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程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
