模版的写法如下:
templates/test3.htm:
<html>
<head>
<title>巢状循环测试</title>
</head>
<body>
<table width="200" border="0" align="center" cellpadding="3" cellspacing="0">
<{section name=sec1 loop=$forum}>
<tr>
<td colspan="2"><{$forum[sec1].category_name}></td>
</tr>
<{section name=sec2 loop=$forum[sec1].topic}>
<tr>
<td width="25"> </td>
<td width="164"><{$forum[sec1].topic[sec2].topic_name}></td>
</tr>
<{/section}>
<{/section}>
</table>
</body>
</html>
执行的结果就像笔者举的例子一样。
因此呢,在程序中我们只要想办法把所要重复值一层一层的塞到数组中,再利用 <{第一层数组[循环1].第二层数组[循环2].第三层数组[循环3]. ... .数组索引}> 这样的方式来显示每一个巢状循环中的值。至于用什么方法呢?下一节使用数据库时我们再提。
转换数据库中的资料 上面提到如何显示巢状循环,而实际上应用时我们的资料可能是从数据库中抓取出来的,所以我们就得想办法把数据库的资料变成上述的多重数组的形式。这里笔者用一个 DB 类别来抓取数据库中的资料,您可以自行用您喜欢的方法。
我们只修改 PHP 程序,模版还是上面那个 (这就是模版引擎的好处~),其中 $db 这个对象假设已经在 main.php 中建立好了,而且抓出来的资料就是上面的例子。
test3.php:
<?php
require "main.php";
// 先建立第一层数组
$category = array();
$db->setSQL($SQL1, 'CATEGORY');
if (!$db->query('CATEGORY')) die($db->error());
// 抓取第一层循环的资料
while ($item_category = $db->fetchAssoc('CATEGORY'))
{
// 建立第二层数组
$topic = array();
$db->setSQL(sprintf($SQL2, $item_category['category_id']), 'TOPIC');
if (!$db->query('TOPIC')) die($db->error());
// 抓取第二层循环的资料
while ($item_topic = $db->fetchAssoc('TOPIC'))
{
// 把抓取的数据推入第二层数组中
array_push($topic, $item_topic);
}
// 把第二层数组指定为第一层数组所抓取的数据中的一个成员
$item_category['topic'] = $topic;
// 把第一层数据推入第一层数组中
array_push($category, $item_category);
}
$tpl->assign("forum", $category);
$tpl->display("test3.htm");
?>
共9页: 上一页 [1] [2] [3] [4] [5] [6] [7] 8 [9] 下一页