【问题标题】:PHP : How can i get the result "B,C" or "C,B"PHP:我怎样才能得到结果“B,C”或“C,B”
【发布时间】:2022-01-19 11:07:39
【问题描述】:

大家好,帮我解决这个问题,先谢谢了

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'));

结果应该是“B,C”或“C,B”。

【问题讨论】:

    标签: php arrays function class object


    【解决方案1】:

    您可以使用以下内容(未测试):

    将带有addCategory() 的类别存储在数组$categories 中,以便您可以使用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"
    

    in action

    【讨论】:

    • 谢谢@berend
    • 不客气!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多