The example in this article describes how to use smarty’s built-in function foreach, and shares it with everyone for your reference. The details are as follows:
Display file: index.php:
$arr1 = array("Beijing","Shanghai","Guangzhou");//Index array
$smarty->assign("arr1",$arr1);//Assign index array
$arr2 = array("city1"=>"Beijing","city2"=>"Shanghai","city3"=>"Guangzhou");//Associative array
$smarty->assign("arr2",$arr2);//Assign associative array
$arr3 = array(array("Beijing","Shanghai","Guangzhou"),array("Guan Yu","Zhang Fei","Beauty"));//Two-dimensional index array
$smarty->assign("arr3",$arr3);
$arr4 = array(array("c1"=>"Beijing","c2"=>"Shanghai","c3"=>"Guangzhou"),array("n1"=>"Guan Yu", "n2"=>"Zhang Fei","n3"=>"Beauty"));//Two-dimensional associative array
$smarty->assign("arr4",$arr4);
$smarty->display("temp.tpl");
?>
Template file: temp.tpl
Example 1: One-dimensional index array
Example 2: One-dimensional associative array——>item is the key value and key is the key name. If the key is not retrieved, the extraction method is the same as the one-dimensional index array. Of course, the index array also has keys 0, 1, 2...
Example 3: Two-dimensional index array——>Two loops are enough
Example 4: Two-dimensional associative array——>Just loop twice
I hope this article will be helpful to everyone’s PHP programming design.