-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
我更新了我的答案,告訴你如何去做你所需要的。 –