無限分類 php 遞歸

本功能是基於thinkphp 框架,已成功如圖:php

/////本地數據庫數據

//最後生成樣式

 

//調用

$NewsCategory = D('NewsCategory');
$newscategory =$NewsCategory ->select();thinkphp

$result =$NewsCategory ->gettree($newscategory);
$select ="<select name='category'>".$result."</select>";

$this ->assign('result', $select);數據庫

本人已親測,就這樣完美的結束了,嘿嘿。。。數組

 

<?php
namespace Admin\Model;
use Think\Model;
class NewsCategoryModel extends Model{框架

public function getList($data, $pid=0){this

// dump($data);exit;
$newarray =array();
if(is_array($data)){
foreach($data as $key=> $value){spa

if($value['pid'] == $pid){
$newarray[$key] =$value;
}
}
}
return $newarray ? $newarray : false;
}blog

 

//生成下拉框列表

/*
* 獲取下拉框
* @param $data 待處理的數組
* @param $pid 得到這個ID下的子級
* @param $cate 被選中的ID
* @param $str 生成下拉框的字符串
*
*
* */遞歸

 

public function gettree($data, $pid=0, $cate, &$str){
$child =$this->getList($data, $pid);  //獲取每個id的子集

if(is_array($child)){
foreach ($child as $key => $value) {
$size =sizeof(explode("-",$value['level']));
$k = intval($size * 2);
$nstr="|";
for($j=1;$j<=$k;$j++){
$nstr.="--";   //加縮進
}字符串

$str .="<option value='".$value['news_category_id']."'>".$nstr.$value['name']."</option>";

$this->gettree($data, $value['news_category_id'], $str);

}
}
return $str;
}

 

//生成數組按表格的形式輸出

public function gettreearray($data, $pid=0, &$str){
$child =$this->getList($data, $pid);

if(is_array($child)){
foreach ($child as $key => $value) {
$size =sizeof(explode("-",$value['level']));
$k = intval($size * 2);
$nstr="|";
for($j=1;$j<=$k;$j++){
$nstr.="--";
}
$str.="<tr>
<td>".$value['news_category_id']."</td>
<td>".$nstr.$value['name']."</td>
<td>".$value['sort']."</td>

<td>
<a href='".U("Admin/NewsCategory/edit?id=".$value['news_category_id'])."'>編輯</a>
<a href='".U("Admin/NewsCategory/addnewcategory?id=".$value['news_category_id'])."'>添加子分類</a>
<a href='".U("Admin/NewsCategory/delete?id=".$value['news_category_id'])."'>刪除</a>
</td>
</tr>";
$this->gettreearray($data, $value['news_category_id'], $str);   //遞歸調用
}
}
return $str;
}

}

相關文章
相關標籤/搜索