这个类将一个扁平的分类数组转换成一个结构化的树形数组:
<?php
class CategoryTree {
protected $categories = array();
protected $tree = array();
function __construct(array $categories) {
$this->categories = $categories;
}
protected function getSubtree(array $categories, $parentId = 0) {
$tree = array();
foreach($categories as $category) {
if($category['suboff'] == $parentId) {
$tree[$category['id']] = $category;
$tree[$category['id']]['children'] = $this->getSubtree($categories, $category['id']);
}
}
return $tree;
}
public function getTree() {
if(empty($this->tree)) {
$this->tree = $this->getSubtree($this->categories, 0);
}
return $this->tree;
}
public function __toString() {
return "<pre>" . print_r($this->getTree(), true) . "</pre>";
}
}
$categories = array(
array(
'id' => 1,
'category' => 'software',
'suboff' => 0
),
array(
'id' => 2,
'category' => 'programming',
'suboff' => 1
),
array(
'id' => 3,
'category' => 'Testing',
'suboff' => 1
),
array(
'id' => 4,
'category' => 'Designing',
'suboff' => 1
),
array(
'id' => 5,
'category' => 'Hospital',
'suboff' => 0
),
array(
'id' => 6,
'category' => 'Doctor',
'suboff' => 5
),
array(
'id' => 7,
'category' => 'Nurses',
'suboff' => 5
),
array(
'id' => 9,
'category' => 'Teaching',
'suboff' => 0
),
array(
'id' => 10,
'category' => 'php programming',
'suboff' => 2
),
array(
'id' => 11,
'category' => '.net programming',
'suboff' => 2
)
);
$myTree = new CategoryTree($categories);
echo $myTree;
?>