This article describes the use of Smarty built-in function foreach, shared for everyone to reference. Specifically as follows:
Display file: index.php:
Copy Code code as follows:
<?php
Creating Smarty Objects
Require_once ("./libs/smarty.class.php");
$smarty = new Smarty ();
$arr 1 = Array ("Beijing", "Shanghai", "Guangzhou");//index array
$smarty->assign ("arr1", $arr 1);//Allocate index array
$arr 2 = Array ("City1" => "Beijing", "City2" => "Shanghai", "City3" => "Guangzhou");//associative array
$smarty->assign ("arr2", $arr 2);//Allocate associative array
$arr 3 = Array ("Beijing", "Shanghai", "Guangzhou"), Array ("Guan Yu", "Zhang Fei", "Beauty"));//two-dimensional indexed array
$smarty->assign ("Arr3", $arr 3);
$arr 4 = Array ("C1" => "Beijing", "C2" => "Shanghai", "C3" => "Guangzhou"), Array ("N1" => "Guan Yu", "N2" => "Zhang Fei", "N3" => "Beauty")) ;//two-dimensional associative array
$smarty->assign ("Arr4", $arr 4);
$smarty->display ("Temp.tpl");
?>
Template file: Temp.tpl
Copy Code code as follows:
<p style= "Color:green" > Instance 1: one-dimensional indexed array </p>
{foreach from= $arr 1 item=temp}
{$temp}
{/foreach}
<p style= "Color:orange" > Instance 2: One-dimensional associative array-->item is the key value and key is the key name. If you do not take the key, the extraction method is the same as the one-dimensional index array, and the index array is also the key 0,1,2...</p>
{foreach from= $arr 2 item=temp key=k}
{$k}={$temp}
{/foreach}
<p style= "Color:red" > Example 3: Two-dimensional indexed array--> two cycles can </p>
{foreach from= $arr 3 item=temp}
{foreach from= $temp item=value}
{$value}
{/foreach}<br/>
{/foreach}
<p style= "color:red" > Example 4: Two-dimensional associative array--> the same two cycles can be </p>
{foreach from= $arr 4 item=temp}
{foreach from= $temp item=value key=k}
{$k}={$value}
{/foreach}<br/>
{/foreach}
I hope this article will help you with your PHP program design.