laravel 使用递归实现无限分类(转自oschina姚棉伟原创)

实现规格:一个新闻无线分类系统最终实现的效果如下
ㅣㅡㅡ体育新闻
ㅣㅡㅡㅡㅡ足球新闻
ㅣㅡㅡㅡㅡ篮球新闻
ㅣㅡㅡㅡㅡ其他体育
ㅣㅡㅡ娱乐新闻
ㅣㅡㅡㅡㅡ电影
ㅣㅡㅡㅡㅡ音乐
ㅣㅡㅡ科技新闻
ㅣㅡㅡㅡㅡ智能手机
ㅣㅡㅡㅡㅡㅡㅡ小米手机
ㅣㅡㅡㅡㅡㅡㅡ华为手机

laravel Model层实现获取分类信息(使用递归)



namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class Category extends Model
{
    protected $table = 'category';
    protected $primaryKey='CategoryID';
    public $timestamps=false;

    //使用递归获取分类 (正式函数)
    public function getCategory($sourceItems, $targetItems, $pid=0){
        foreach ($sourceItems as $k => $v) {
            if($v->pid == $pid){
                $targetItems[] = $v;
                $this->getCategory($sourceItems, $targetItems, $v->CateID);
            }
        }
    }

    //使用递归获取分类信息测试函数 (测试正式函数)
    public function getCategoryTest($sourceItems, $targetItems, $pid=0, $str='ㅣ'){
        $str .= 'ㅡㅡ';
        foreach ($sourceItems as $k => $v) {
            if($v->pid == $pid){
                $v->CateName = $str.$v->CateName;
                $targetItems[] = $v;
                $this->getCategoryTest($sourceItems, $targetItems, $v->CateID, $str);
            }
        }
    }

    //使用递归获取分类信息 (正式函数)
    public function getCategoryInfo(){
        $sourceItems = $this->get();
        $targetItems = new Collection;
        $this->getCategory($sourceItems, $targetItems, 0);
        return $targetItems;
    }

    //测试函数 (测试正式函数)
    public function getCategoryInfoTest(){
        $sourceItems = $this->get();
        $targetItems = new Collection;
        $this->getCategoryTest($sourceItems, $targetItems);
        return $targetItems;
    }

}

laravel ctroller层实现测试效果



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Model\Category;
use Illuminate\Database\Eloquent\Collection;
use DB;

class CategoryCtroller extends Controller
{
    public function index(){
        $category = new Category;
        $items = $category->getCategoryInfoTest();
        foreach ($items as $key => $item) {
            dump($item->CateName);
        }

    }
}

访问相关的控制器就可看见要实现的无限分类的效果

你可能感兴趣的:(php,laravel)