categories - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of categories.php
- <?php
- class CategoryTree
- {
- private $a = [];
- public function addCategory(string $category, string $parent=null): void
- {
- $validParent = false;
- if ($parent === null)
- $validParent = true;
- foreach ($this->a as $e)
- {
- if ($e["name"] === $category)
- throw new InvalidArgumentException('Category exists!');
- if ($parent === null || ($e["name"] === $parent && $parent != null))
- $validParent = true;
- }
- if (!$validParent)
- throw new InvalidArgumentException('Parent does not exist!');
- array_push($this->a, array("name" => $category, "parent" => $parent));
- }
- public function getChildren(string $parent): array
- {
- $childrenArr = [];
- foreach ($this->a as $e)
- if ($e["parent"] === $parent)
- array_push($childrenArr, $e["name"]);
- return $childrenArr;
- }
- }
- $c = new CategoryTree;
- $c->addCategory('A', null);
- $c->addCategory('B', 'A');
- $c->addCategory('C', 'e');
- echo implode(',', $c->getChildren('A'));