一、smarty两种循环输出数据的方法:
<?php
include_once(“Smarty_inc.php”);
$conn=mysql_connect(“localhost”,”root”,””);
mysql_select_db(“news”,$conn);
$sql=”select * from news_table order by id desc”;
mysql_query(“set names ‘UTF8′”);
$query=mysql_query($sql);
while($rows=mysql_fetch_array($query))//第一种
{
$arr[]=array(“id”=>$rows[id],”title”=>$rows[title]);
}
$smarty->assign(“rows”,$arr);
$smarty->display(“user_b.htm”);//第二种
//{
//$smarty->assign(“rows”,$rows);
//$smarty->display(“user_b.htm”);
//}
模板代码:
针对第二种:
编号:{$rows[‘id’]}<br />
标题:{$rows[‘title’]}<br />
第一种:
{section name=list loop=$rows}
编号:{$rows.id}<br />
标题:{$rows.title}
<hr />
{/section}
</body>
</html>
{/section}
二、foreach循环输出数组
foreach是除section之外处理循环的另一种方案(根据不同需要选择不同的方案).
foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组.
foreach 必须和 /foreach 成对使用,且必须指定 from 和 item 属性.
name 属性可以任意指定(字母、数字和下划线的组合).
foreach 可以嵌套,但必须保证嵌套中的 foreach 名称唯一.
from 属性(通常是数组)决定循环的次数.
foreachelse 语句在 from 变量没有值的时候被执行.
foreach 输出数组键/值的示例:
{* The key contains the key for each looped value
assignment looks like this:
$smarty->assign(“contacts”, array(array(“phone” => “1”, “fax” => “2”, “cell” => “3”),
array(“phone” => “555-4444”, “fax” => “555-3333”, “cell” => “760-1234”)));
*}
{* 键就是数组的下标,请参看关于数组的解释 *}{foreach name=outer item=contact from=$contacts}
{foreach key=key item=item from=$contact}
{$key}: {$item}<br>
{/foreach}
{/foreach}
OUTPUT:
phone: 1<br>
fax: 2<br>
cell: 3<br>
phone: 555-4444<br>
fax: 555-3333<br>
cell: 760-1234<br>
三、section循环输出数组演示
Smarty模板的section用于遍历数组中的数据。
section标签必须成对出现,必须设置name和loop属性. 名称可以是包含字母、数字和下划线的任意组合.
可以嵌套但必须保证嵌套的name唯一.
变量 loop (通常是数组)决定循环执行的次数.
当需要在section循环内输出变量时,必须在变量后加上中括号包含着的name变量.
{section name=customer loop=$custid}
id: {$custid[customer]}
name: {$name[customer]}
address: {$address[customer]}
{/section}
在这个奇怪的语法中,name必须像数组中的索引值一样引用。还要注意,$custid变量名有双得的职责,它既是循环的指示器,也是实际的
变量引用。
OUTPUT:
id: 1000
name: John Smith
address: 253 N 45th
id: 1001
name: Jack Jones
address: 417 Mulberry ln
id: 1002
name: Jane Munson
address: 5605 apple st
四、section 嵌套循环
Section可以按照你的需要嵌套,在sections中的嵌套中,你可以访问复杂的数据结构,比如多维数据,
{section name=customer loop=$custid}
id: {$custid[customer]}
name: {$name[customer]}
address: {$address[customer]}
{section name=contact loop=$contact_type[customer]}
{$contact_type[customer][contact]}: {$contact_info[customer][contact]}
{/section}
{/section}
评论