- array_push: documentation ( source)
- array_shift: documentation ( source)
- array_pop: documentation ( source)
<?php
class category {
public $name;
public $subCats = array();
public function __construct($name = "") {
$this->name = $name;
}
public function add_sub_cat($subCat) {
array_push($this->subCats, $subCat);
}
}
function tree_print($root_category) {
$stack = array(array($root_category));
echo '<ul>'."\n";
while (count($stack)) {
$category = array_shift($stack[count($stack)-1]);
echo '<li><div id="category-name"><p>' . $category->name . '</p></div></li>'."\n";
echo '<ul>'."\n";
$stack[] = $category->subCats;
while (count($stack) && count($stack[count($stack)-1]) == 0) {
echo '</ul>'."\n";
array_pop($stack);
}
}
}
$x = new category('root');
$x->add_sub_cat(new category('foo'));
$x->add_sub_cat(new category('bar'));
$x->subCats[0]->add_sub_cat(new category('baz'));
$x->subCats[1]->add_sub_cat(new category('baz2'));
tree_print($x);