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.



Your result can be seen below.

Result of php executing





Full code of categories.php

  1. <?php
  2.  
  3. class CategoryTree
  4. {
  5.     private $a = [];
  6.     
  7.     public function addCategory(string $category, string $parent=null): void
  8.     {
  9.         $validParent = false; 
  10.         if ($parent === null)
  11.             $validParent = true;
  12.         foreach ($this->a as $e)
  13.         {
  14.             if ($e["name"] === $category)
  15.                 throw new InvalidArgumentException('Category exists!');
  16.             if ($parent === null || ($e["name"] === $parent && $parent != null))
  17.                 $validParent = true;
  18.         }
  19.         if (!$validParent)
  20.             throw new InvalidArgumentException('Parent does not exist!');
  21.  
  22.         array_push($this->a, array("name" => $category, "parent" => $parent));
  23.     }
  24.     
  25.     public function getChildren(string $parent): array
  26.     {
  27.         $childrenArr = [];
  28.         foreach ($this->a as $e)
  29.             if ($e["parent"] === $parent)
  30.                 array_push($childrenArr, $e["name"]);
  31.         return $childrenArr;
  32.     }
  33. }
  34.  
  35. $c = new CategoryTree;
  36. $c->addCategory('A', null);
  37. $c->addCategory('B', 'A');
  38. $c->addCategory('C', 'e');
  39.  
  40. echo implode(',', $c->getChildren('A'));
  41.  
File Description
  • categories
  • PHP Code
  • 27 Jun-2022
  • 1.08 Kb
You can Share it: