Home > Backend Development > PHP Tutorial > smarty模板引擎使用内建函数foreach循环取出所有数组值的方法_PHP

smarty模板引擎使用内建函数foreach循环取出所有数组值的方法_PHP

WBOY
Release: 2016-05-31 13:17:10
Original
825 people have browsed it

本文实例讲述了smarty内建函数foreach的使用方法,分享给大家供大家参考。具体如下:

显示文件:index.php:

代码如下:

//创建smarty对象
require_once("./libs/Smarty.class.php");
$smarty = new Smarty();

$arr1 = array("北京","上海","广州");//索引数组
$smarty->assign("arr1",$arr1);//分配索引数组
$arr2 = array("city1"=>"北京","city2"=>"上海","city3"=>"广州");//关联数组
$smarty->assign("arr2",$arr2);//分配关联数组
$arr3 = array(array("北京","上海","广州"),array("关羽","张飞","美女"));//二维索引数组
$smarty->assign("arr3",$arr3);
$arr4 = array(array("c1"=>"北京","c2"=>"上海","c3"=>"广州"),array("n1"=>"关羽","n2"=>"张飞","n3"=>"美女"));//二维关联数组
$smarty->assign("arr4",$arr4);

$smarty->display("temp.tpl");
?>

模板文件:temp.tpl

代码如下:


smarty内建函数foreach,循环取出数组值


实例1:一维索引数组


{foreach from=$arr1 item=temp}
{$temp}
{/foreach}

实例2:一维关联数组——>item为键值,key为键名。如果不取key,取出方法与一维索引数组相同,当然索引数组也是有key的0,1,2...


{foreach from=$arr2 item=temp key=k}
{$k}={$temp}
{/foreach}

实例3:二维索引数组——>两次循环即可


{foreach from=$arr3 item=temp}
 {foreach from=$temp item=value}
  {$value}
 {/foreach}

{/foreach}

实例4:二维关联数组——>同样两次循环即可


{foreach from=$arr4 item=temp}
 {foreach from=$temp item=value key=k}
  {$k}={$value}
 {/foreach}

{/foreach}

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template