這是我目前撈取上下關聯目錄的方式,不知道有沒有更好的方法
PHP 部分
// 撈取大目錄
$cate = array();
$sqlC1 = "SELECT id, label FROM category ORDER BY id ASC";
$queryC1 = $db->myRow($sqlC1);
foreach($queryC1 as $x => $rowC1) {
$cate[$x]['id'] = $rowC1['id'];
$cate[$x]['label'] = $rowC1['label'];
// 撈取中目錄
$sqlC2 = sprintf("SELECT id, label FROM category WHERE parent_id = %s ORDER BY id ASC",
$rowC1['id']);
$queryC2 = $db->myRow($sqlC2);
$cate[$x]['c2'] = array();
foreach ($queryC2 as $y => $rowC2) {
$cate[$x]['c2'][$y]['id'] = $rowC2['id'];
$cate[$x]['c2'][$y]['label'] = $rowC2['label'];
}
}
$smarty->assign('cate', $cate);
Template 部分
{if $cate}
{section name=data loop=$cate}
{$cate[data].label}
{if $cate[data].c2}
{section name=data2 loop=$cate[data].c2}
{$cate[data].c2[data2].label}
{/section}
{/if}
{/section}
{/if}
用一個 sql 就能查出你想要的結果:
<pre class="c" name="code">select A.id,A.label,B.id,B.label
from category as A left join category as B
on B.parent_id=A.id
where A.parent_id is null
order by A.id,B.id
PS. 因為你 $sqlC1 沒寫 where 條件,會連第二層也抓出,所以我加上 where A.parent_id is null 來限制。假如這不是你要的效果,請自行修改。
對,我漏了一個判斷,請問這樣怎麼 assign 會達到效果
$cate = array();
$sqlC1 = "select A.id as pid ,A.label as plabel,B.id,B.label
from category as A left join category as B
on B.parent_id=A.id
where A.parent_id is null
order by A.id,B.id";
$queryC1 = $db->myRow($sqlC1);
foreach($queryC1 as $x => $rowC1) {
$cate[$x]['id'] = $x;
$cate[$x]['label'] = $rowC1['plabel'];
$cate[$x]['c2'][$rowC1['id']]['id'] = $rowC1['id'];
$cate[$x]['c2'][$rowC1['id']]['label'] = $rowC1['label'];
}
$smarty->assign('cate', $cate);
不對啊,這樣 level 1 的 label 會因為該 level 2 有多少資料就重複多少次啊
<pre class="c" name="code">
$sql = "SELECT a.t_id AS a_id, a.t_label AS a_label, a.t_level AS a_level, b.t_id AS b_id, b.t_label AS b_label, b.t_level AS b_level, c.t_id AS c_id, c.t_label AS c_label FROM tbl_cate a LEFT JOIN tbl_cate b ON b.parent_id = a.t_id LEFT JOIN tbl_cate c ON c.parent_id = b.t_id WHERE a.t_level = 1 ORDER BY a.t_id ASC, b.t_id ASC";
$query = $chan->myRow($sql);
$cate = array();
foreach ($query as $k => $row) {
$cate[$row['a_id']]['a_id'] = $row['a_id'];
$cate[$row['a_id']]['a_label'] = $row['a_label'];
$cate[$row['b_id']]['b_id'] = $row['b_id'];
$cate[$row['b_id']]['b_label'] = $row['b_label'];
$cate[$row['c_id']]['c_id'] = $row['c_id'];
$cate[$row['c_id']]['c_label'] = $row['c_label'];
}
$smarty->assign('cate', $cate);
$smarty->display('cate.html')
<pre class="c" name="code"> {foreach $cate as $v}
<div>{$v.a_label}</div>
<div class="level2">{$v.b_label}</div>
<div class="level3">{$v.c_label}</div>
{/foreach
剛發現這樣就可以了