1
创建用于PHP数组树结构数据的JSON数据我有类别表:使用递归函数
CategoryID CategoryName ParentID
1 Root Null
2 News 1
3 Horoscope 1
4 Sports 2
5 National 2
6 Daily 3
7 Aries 6
8 Weekly 3
9 Aries 8
我想如下创建树状结构的JSON数据:
[{
"id":1,
"text":"Root",
"children":[{
"id":2,
"text":"News",
"state":"closed",
"children":[{
"id":4,
"text":"Sports"
},{
"id":5,
"text":"National"
}]
},{
"id":3,
"text":"Horoscope",
"children":[{
"id":6,
"text":"Daily",
"children":[{
"id":7,
"text":"Aries"
}],
},{
"id":8,
"text":"Weekly",
"children":[{
"id":9,
"text":"Aries"
}],
}
}]
}]
我有以下功能呈现所有类别和子类别
public function categoryData($parent)
{
$model=new Category();
$cat=$model->findAllByAttributes(array('ParentCategoryID'=>$parent,'Status'=>2));
$category = array();
foreach($cat as $record)
{
global $category;
$category['id'][$record->CategoryID] = $record->CategoryID;
$category['text'][$record->CategoryID] = $record->CategoryName;
// $category['children'][$record->CategoryID] = array();
//$names[] = $record->CategoryName;
$this->categoryData($record->CategoryID);
}
//array_push($category['children'][$record->ParentCategoryID], $category['children'][$record->CategoryID]);
return $category;
}
问题: 但上面的操作并没有以适当的格式放置数组中的类别,因此我可以通过应用json_encode($ category)函数来创建上述json数据格式。
如何使用树结构数组中的递归函数放置类别数据?
你想看看这个问题http://stackoverflow.com/questions/4196157/create-array-tree-from-array-名单 – antony 2013-04-20 13:55:15