无限分类 php 递归
本功能是基于thinkphp 框架,已成功如图:
/////本地数据库数据
//最后生成样式
//调用
$NewsCategory = D('NewsCategory');
$newscategory =$NewsCategory ->select();
$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){
// dump($data);exit;
$newarray =array();
if(is_array($data)){
foreach($data as $key=> $value){
if($value['pid'] == $pid){
$newarray[$key] =$value;
}
}
}
return $newarray ? $newarray : false;
}
//生成下拉框列表
/*
* 获取下拉框
* @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;
}
}