In this paper, the use of smarty built-in function foreach is described and shared for everyone's reference. Specific as follows:
Display file: index.php:
Copy the Code code as follows: <?php
Create a Smarty Object
Require_once ("./libs/smarty.class.php");
$smarty = new Smarty ();
$arr 1 = Array ("Beijing", "Shanghai", "Guangzhou");//indexed array
$smarty->assign ("arr1", $arr 1);//Assigning an indexed array
$arr 2 = Array ("city1" = "Beijing", "City2" and "Shanghai", "City3" and "Guangzhou");//associative array
$smarty->assign ("arr2", $arr 2);//Assigning associative arrays
$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" and "Beijing", "C2" and "Shanghai", "C3" and "Guangzhou"), Array ("N1" and "Guan Yu", "n2" = "Zhang Fei", "N3" and "Beauty") ;//two-dimensional associative array
$smarty->assign ("Arr4", $arr 4);
$smarty->display ("Temp.tpl");
?>
Template file: Temp.tpl
Copy the Code code as follows:
Smarty built-in function foreach, loops out the array value
Example 1: one-dimensional indexed array
{foreach from= $arr 1 item=temp}
{$temp}
{/foreach}
Example 2: one-dimensional associative array-->item is a key value, key is the name. If you do not take the key, the extraction method is the same as the one-dimensional index array, of course, the index array is also a key 0,1,2 ...
{foreach from= $arr 2 item=temp key=k}
{$k}={$temp}
{/foreach}
Example 3: Two-dimensional index array--two cycles
{foreach from= $arr 3 item=temp}
{foreach from= $temp item=value}
{$value}
{/foreach}
{/foreach}
Example 4: Two-dimensional associative array-and two cycles
{foreach from= $arr 4 item=temp}
{foreach from= $temp item=value key=k}
{$k}={$value}
{/foreach}
{/foreach}
I hope this article is helpful to everyone's PHP programming.