-1
This is the db structure笨树视图构建数据
[
{
text: 'Parent 1',
href: '#parent1',
tags: ['4'],
nodes: [
{
text: 'Child 1',
href: '#child1',
tags: ['2'],
nodes: [
{
text: 'Grandchild 1',
href: '#grandchild1',
tags: ['0']
},
{
text: 'Grandchild 2',
href: '#grandchild2',
tags: ['0']
}
]
},
{
text: 'Child 2',
href: '#child2',
tags: ['0']
}
]
},
{
text: 'Parent 2',
href: '#parent2',
tags: ['0']
},
{
text: 'Parent 3',
href: '#parent3',
tags: ['0']
}
]
我使用的代码是这样的,
public function getCategoryTree($level = 0, $prefix = '') {
$rows = $this->db
->select('id,parent_id,name')
->where('parent_id', $level)
->order_by('id','asc')
->get('category')
->result();
$json_response = array();
foreach ($rows as $row)
{
$row_array = array();
$row_array['text'] = $row->name;
$row_array['nodes'] = array();
$newlevel = $row->id;
$childs = $this->db
->select('id,parent_id,name')
->where('parent_id', $newlevel)
->order_by('id','asc')
->get('category')
->result();
if(count($childs) > 0){
foreach ($childs as $row)
{
$row_array['nodes'][] = array(
'text' => $row->name,
);
}
}
array_push($json_response, $row_array); //push the values in the array
}
return $json_response;
}
输出我得到: output
上面的代码仅给出一个水平,但我想深入。如何格式化循环以完成它?
不要把数据库结构的图像。 – aristotll
我更新了我的答案,告诉你如何去做你所需要的。 –