Home > Backend Development > PHP Tutorial > Smarty built-in function foreach usage example, smartyforeach_PHP tutorial

Smarty built-in function foreach usage example, smartyforeach_PHP tutorial

WBOY
Release: 2016-07-13 10:09:16
Original
857 people have browsed it

usage example of smarty built-in function foreach, smartyforeach

The example in this article describes the usage of smarty’s built-in function foreach. Share it with everyone for your reference. The details are as follows:

Output file: index.php

Copy code The code is as follows:
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("Xi Yang Yang", "美 Yang Yang", "Lazy Yang", "Ha Ha Ha");
$family = array("husband"=>"Xi Yangyang","wife"=>"Mei Yangyang","boy"=>"Lazy Yang","girl"=>"Hahaha");
$smarty->assign("name",$name);
$smarty->assign("family",$family);

$smarty->display("temp.htm");
?>

Template file: temp.htm

Copy code The code is as follows:
{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}

There are roughly two forms of array output methods:

(1) One is smarty 2’s {foreach from=array variable name item=array value}.
(2) The output method of smarty 3 is consistent with that of PHP. The above example does not add $key. When you need to output the key name, use the form @key in the example; you can use the form $key=>$value.

In addition, if you only take a certain value in the array, you can output it directly, such as {$family.husband} for associative arrays, {$name[0]} for index arrays, etc.

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/946756.htmlTechArticlesmarty built-in function foreach usage example, smartyforeach This article describes the usage of smarty built-in function foreach. Share it with everyone for your reference. The details are as follows: Output file: index.p...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template