This article mainly introduces the usage of the smarty built-in function foreach. The example analyzes the usage skills and precautions of the smarty built-in foreach function. For more information, see
This article mainly introduces the usage of the smarty built-in function foreach. The example analyzes the usage skills and precautions of the smarty built-in foreach function. For more information, see
This example describes the usage of the smarty built-in function foreach. Share it with you for your reference. The details are as follows:
Output file: index. php
The Code is as follows:
<? 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 ("xiyangyang", "meiyang", "lazy", "HAHAHA ");
$ Family = array ("husband" => "Xiyang", "wife" => "meiyang", "boy" => "lazy ", "girl" => "HAHAHA ");
$ Smarty-> assign ("name", $ name );
$ Smarty-> assign ("family", $ family );
$ Smarty-> display ("temp.htm ");
?>
Template File: temp.htm
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}
The output method of the array can be roughly two forms:
(1) One is {foreach from = array variable name item = array value} of smarty 2 }.
(2) the output method of smarty 3 is the same as that of php. The above instance does not add $ key. When a key name needs to be output, @ key is used in the form of an instance; you can use $ key => $ value.
In addition, if only one value in the array is obtained, it can be output directly, for example, the {$ family. husband} of the associated array and the {$ name [0]} of the index array.
I hope this article will help you with php programming.
,