作者liaosankai (低温烘焙)
标题Re: [请益] 巢状资料组合阵列
时间Fri Nov 22 01:37:28 2013
※ 引述《chan15 (ChaN)》之铭言:
: 分类的 table 为 categories,结构如下
: id primary key
: name varchar
: order int
: category_id int NULL
: 如果 category_id 是 NULL 的话,就是第一层,order 同时也为 0,今天需要将双层的目录捞出後 output 成 JSON 格式
: {
: "Category":
: [
: {
: "first_name":"a1",
: "second_category":
: [
: "second_name":"a1-1",
: "second_name":"a1-2"
: ]
: }
: ],[
: {
: "first_name":"a2",
: "second_category":
: [
: "second_name":"a2-1",
: "second_name":"a2-2",
: "second_name":"a2-3"
: ]
: }
: ]
: }
: 我的 framework 是 Laravel,所以写法为
: $result = [];
: $category = Category::whereNull('category_id')->with('categories);
: if (NULL !== $category) {
: foreach ($category->get() as $k => $first) {
: $result['Category'][$k]['first_name'] = $first->name;
: if (NULL !== $first->children) {
: foreach ($first->children as $j => $second) {
: $result['Category'][$k]['second_category'][$j]['second_name'] = $second->name;
: }
: }
: }
: }
: return Response::json($result);
: 不知道有没有更精简的做法,假设今天要取到三层,会变的很长
: $result['Category'][$k]['second_category'][$j]['third_name'][$i] = $third->name;
: ※ 编辑: chan15 来自: 1.34.249.126 (11/21 11:17)
=.= 又有一阵子没写 Laravel4 了,有点忘记一些规则。下面的程式是从之前写的
Kohana 改成 Laravel4 版本的,我有做基本的测试了,你可以改成属於你自己的规则。
### 资料表结构 ###
categores
- id
- name
- rank
- parent_id
### 程式码 ###
class Category extends Eloquent {
protected $table = 'categores';
public function children() {
return $this->hasMany('Category', 'parent_id');
}
public static function tree() {
$root = self::where('parent_id','=',0)->orderBy('rank')->get();
return self::recurse_tree($root);
}
public static function recurse_tree($categories, $tree=array()){
foreach($categories as $key => $category) {
$tree[$key] = $category->toArray();
$children = $category->children()->orderBy('rank')->get();
if($children) {
$tree[$key]['children'] = array();
$tree[$key]['children'] = self::recurse_tree
($children, $tree[$key]['children']);
}
}
return $tree;
}
}
### 控制器 ###
class HomeController extends Controller {
public function index() {
print_r(Category::tree());
}
}
建议结构不要超过三层会比较好,不然就考虑研究 MTPP 演算法的方式
可以参考之前乡民讨论的到部分
http://goo.gl/h5d40d
另外 Eloquent 强化过会比较好用,可以参考文章
http://goo.gl/CbxVx1
--
欢迎来我的网志看看
@
http://blog.liaosankai.com
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.126.240.101
※ 编辑: liaosankai 来自: 59.126.19.29 (01/08 10:31)