作者chan15 (ChaN)
看板PHP
标题[请益] 巢状资料组合阵列
时间Thu Nov 21 11:16:52 2013
分类的 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)
1F:推 dlikeayu:最後要转json,不如搞个nosql来玩更快更有效率 11/25 04:41