This article mainly introduces how the smarty template engine uses the built-in function foreach to retrieve all array values in a loop. The example analyzes several common techniques of foreach looping arrays. For more information, see
This article mainly introduces how the smarty template engine uses the built-in function foreach to retrieve all array values in a loop. The example analyzes several common techniques of foreach looping arrays. For more information, see
This article describes how to use the smarty built-in function foreach and shares it with you for your reference. The details are as follows:
Display file: index. php:
The Code is as follows:
<? Php
// Create a smarty object
Require_once ("./libs/Smarty. class. php ");
$ Smarty = new Smarty ();
$ Arr1 = array ("Beijing", "Shanghai", "Guangzhou"); // Index array
$ Smarty-> assign ("arr1", $ arr1); // assign an Index Array
$ Arr2 = array ("city1" => "Beijing", "city2" => "Shanghai", "city3" => "Guangzhou"); // associate an array
$ Smarty-> assign ("arr2", $ arr2); // assign an associated array
$ Arr3 = array ("Beijing", "Shanghai", "Guangzhou"), array ("Guan Yu", "Zhang Fei", "beauty ")); // two-dimensional Index Array
$ Smarty-> assign ("arr3", $ arr3 );
$ Arr4 = array ("c1" => "Beijing", "c2" => "Shanghai", "c3" => "Guangzhou "), array ("n1" => "Guan Yu", "n2" => "Zhang Fei", "n3" => "beauty"); // two-dimensional join array
$ Smarty-> assign ("arr4", $ arr4 );
$ Smarty-> display ("temp. tpl ");
?>
Template File: temp. tpl
The Code is as follows:
Smarty built-in function foreach, which cyclically retrieves array values
Example 1: One-dimensional Index Array
{Foreach from = $ arr1 item = temp}
{$ Temp}
{/Foreach}
Instance 2: one-dimensional join array --> item is the key value, and key is the key name. If the key is not obtained, the retrieval method is the same as the one-dimensional Index Array. Of course, the index array also has the key 0, 1, 2...
{Foreach from = $ arr2 item = temp key = k}
{$ K }={ $ temp}
{/Foreach}
Example 3: Two-dimensional Index Array --> two loops
{Foreach from = $ arr3 item = temp}
{Foreach from = $ temp item = value}
{$ Value}
{/Foreach}
{/Foreach}
Example 4: Two-Dimensional join array --> the same two loops.
{Foreach from = $ arr4 item = temp}
{Foreach from = $ temp item = value key = k}
{$ K }={ $ value}
{/Foreach}
{/Foreach}
I hope this article will help you with php programming.