Home > Mobile >  PHP : How can i get the result "B,C" or "C,B"
PHP : How can i get the result "B,C" or "C,B"

Time:12-16

Hi anyone help me to solve this, thanks in advance

class CategoryTree
{
    public function addCategory(string $category, string $parent=null) : void
    {

    }

    public function getChildren(string $parent) : array
    {
        return [];
    }
}

$c = new CategoryTree;
$c->addCategory('A', null);
$c->addCategory('B', 'A');
$c->addCategory('C', 'A');
echo implode(',', $c->getChildren('A'));

Result should be "B,C" or "C,B".

CodePudding user response:

You could use something like following (not tested):

Store categories with addCategory() in array $categories so you can retrieve them with getChildren().

<?php

class CategoryTree
{
    private $categories = [];

    public function addCategory(string $category, string $parent = null): void
    {
        $this->categories[$parent][] = $category;
    }

    public function getChildren(string $parent): array
    {

        return $this->categories[$parent];
    }
}

$c = new CategoryTree;
$c->addCategory('A', null);
$c->addCategory('B', 'A');
$c->addCategory('C', 'A');
echo implode(',', $c->getChildren('A'));
//Result should be "B,C" or "C,B"

see it in action

  • Related