[英]recursive php category tree extended
我一直在整個論壇中搜索,但是找不到我特定問題的答案。 希望您能為我提供幫助,因為它已經使我花了很多時間才將其作為一名入門的PHP程序員來解決。
我有一個偵聽此URL的頁面:... / ... / edit_cat.php?id = 24
我想要一棵漂亮的類別樹。 我已經做到了,但是我希望所有沒有孩子的類別都鏈接到post.php頁面,而所有確實有孩子的父類別都成為鏈接,但僅顯示其他類別。 您可能會稱其為某種下拉菜單。 因此,post.php中沒有任何子項,如果有子項,則將其余子項丟棄。 我希望這能使事情變得清楚...這是我到目前為止的想法。 它像一棵樹一樣工作,但不是我希望的樣子:
<h2>This is the current category tree</h2>
<?php
category_tree(0);
function category_tree($catid){
include '../config/connect.php';
$result = $db->prepare("SELECT * FROM categories WHERE parent_id = '".$catid."'");
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)):
$i = 0;
if ($i == 0){ echo '<ul class="cattree">';}
echo '<li><a href="category.php?id=' . $row['cat_id'] . '">' . $row['cat_title'] . '</a>';
category_tree($row['cat_id']);
echo '</li>';
$i++;
if ($i > 0){ echo '</ul>'; }
endwhile;
}
?>
我的類別表如下所示:
cat_id | cat_title | parent_id
1 some_title 0
2 some_title 1
3 title! 2
4 main_title 0
5 titellos! 4
這是我去年所做的事情,查詢返回每一行,並帶有該行的idx,parent_idx和標簽。
首次致電:
print_list(1, 0, $lines);
功能:
function print_list($parent, $level, $ar) {
$children = filter_by_parent($parent, $ar);
if (empty($children)) {
return;
}
echo '<ul>';
foreach ($children as $child) {
include PATH_PUBLIC . 'clients/simili/line.php';
print_list($child['Child_Idx'], ($level + 1), $ar);
echo '</li>';
}
echo '</ul>';
}
第二功能:
function filter_by_parent($parent_id, $ar){
$retval = array();
foreach($ar as $a) {
if ($a['Parent_Idx'] == $parent_id) {
$retval[] = $a;
}
}
return $retval;
}
並在函數中調用了html:
<li class="no" data-id="<?php echo $child['Child_Idx']; ?>" data-parent-id="<?php echo $child['Parent_Idx']; ?>">
<i class="fa fa-plus-square-o"></i>
<i class="fa fa-minus-square-o"></i>
<span class="name">
<label><?php echo $child['Child_Name']; ?></label>
<a href="<?php echo url(''); ?>clients/simili/detail.php?uo=<?php echo $child['Child_Idx']; ?>"><i class="fa fa-book" title="Détails de l'Unité d'Organisation"></a></i>
</span>
<div class="chiffres">
<span class="inscrits"><?php echo $child['Nb_Collab']; ?></span>
<span class="etp-collab"><?php echo $child['ETP_Collab']; ?></span>
<span class="etp-postes"><?php echo $child['ETP_Postes']; ?></span>
<span class="etp-unit"><?php echo $child['ETP_Unit']; ?></span>
</div>
好的,我對PHP一無所知,但是這是您可以在SQL查詢中添加“ HasChildren”列的方法:
SELECT c.*,
CASE
WHEN EXISTS(SELECT * FROM Categories c1 WHERE c1.parent_id=c.cat_id) THEN 1
ELSE 0
END AS HasChildren
FROM Categories c
WHERE ParentID = @CatID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.