class vfBuildJSTree {
protected $items = [];
protected $tree = [];
function __construct(array $items) {
$this->items = $items;
}
protected function getSubtree(array $items, $parentId = 0) {
$tree = [];
foreach($items as $item) {
if ($item['parent'] == $parentId) {
unset ($item['parent']);
$tree[$item['id']] = $item;
$tree[$item['id']]['children'] = $this->getSubtree($items, $item['id']);
if (empty($tree[$item['id']]['children'])) {
unset ($tree[$item['id']]['children']);
} else {
$tree[$item['id']]['children'] = array_values($tree[$item['id']]['children']);
}
}
}
return $tree;
}
public function getTree() {
if (empty($this->tree)) {
$this->tree = $this->getSubtree($this->items, 0);
}
return $this->tree;
}
}