[英]Recursive Category Tree in PHP for Edit Page
我在PHP中創建了一個遞歸類別樹,下面是代碼
function categoryTree($parent_id= 0, $sub_mark = ''){
$stmt = $this->db->prepare("SELECT * FROM category WHERE cat_p_id = '".$parent_id."'");
$stmt->execute();
$rowCount = $stmt->rowCount();
if($rowCount > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '<option value="'.$row['cat_id'].'">'.$sub_mark.$row['cat_name'].'</option>';
$this->categoryTree($row['cat_id'], $sub_mark.'--- ', '');
}
}
}
上面的代碼在添加類別時工作正常,問題是在編輯類別時。 如何在編輯時選擇類別?
以下是需求的屏幕截圖:
當您編輯頁面時,將有當前對象要編輯。
current_object = get_current_object_somewhere();
selected_category_id = current_object->category_id;
因此,您具有在編輯時需要突出顯示的selected_category_id
,現在只需在選擇選項中將其標記為selected
:
if($rowCount > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
selected = selected_category_id === $row['cat_id'] ? ' selected' : '';
echo "<option{selected} value='{$row['cat_id']}'>{$sub_mark}{$row['cat_name']}</option>";
$this->categoryTree($row['cat_id'], $sub_mark.'--- ', '');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.