3v4l.org

run code in 300+ PHP versions simultaneously
<?php class CategoryTree { private $catTree = array(); public function addCategory($category, $parent) { if($parent == null){ //echo count(array_column($this->catTree, 'category')); if(count(array_column($this->catTree, 'category', $category)) > 0){ echo 'Duplicate category'; } else{ $temp = array("category" => $category,"parent" => $parent); array_push($this->catTree,$temp); } } else{ echo 'Parent: ' . $parent; print_r(array_column($this->catTree, 'parent', $parent)); echo count(array_column($this->catTree, 'parent', $parent)); } } public function getChildren($parent) { $that = $this; $keys = array_keys(array_column($this->catTree, 'parent'), $parent); return array_map(function($k) use ($that){return $that->catTree[$k]['category'];}, $keys); } } // For testing purposes (do not submit uncommented): $c = new CategoryTree; $c->addCategory('A', null); $c->addCategory('A', null); $c->addCategory('B', 'A'); $c->addCategory('B', 'D'); $c->addCategory('C', 'A'); echo implode(',', $c->getChildren('A'));

preferences:
53.31 ms | 402 KiB | 5 Q