附加对象的数组属性的PHP不起作用

时间:2017-06-12 23:33:57

标签: php arrays properties reference

这是我的代码。我想在数组中添加一个新元素,并且只添加了“faruk”元素。我也需要添加B元素。见下面的代码:     

class CategoryTree
{
    var $root;
    public function CategoryTree() {
        // First element of the array represents the name of the category, so to iterate children, we have to go from index 1
        $this->root=array("root"); 
    }

    // Add category with name $category to parent with name $parent
    public function addCategory($category, $parent)
    {
        if(is_null($parent)) {
            $this->root[]=array($category);
            $this->root[1][]="faruk";
            print "root is: <pre>"; print_r($this->root); print "</pre>";
        } else {
            $rootRef = &$this->root;
            $parentCategory = $this->getCategoryWithNameInSubtree($parent, $rootRef);
            $parentCategory[]=array($category);
            print "<br/>new parent category is: <pre>"; print_r($parentCategory); print "</pre>";
        }
    }

    private function getCategoryWithNameInSubtree($name, $subTreeRoot) {
        // Traverse its direct children
        for($i=1; $i<count($subTreeRoot); $i++) {
            $subCategory = &$subTreeRoot[$i];
            if ($subCategory[0] == $name) {
                echo "<br/>Hey, returning subCategory!";
                return $subCategory;
            }
        }
    }
}

$c = new CategoryTree();
$c->addCategory('A', null);
$c->addCategory('B', 'A');
print "ct is: <pre>"; print_r($c); print "</pre>";

为什么不将B添加到树中?结果是:

CategoryTree Object
(
    [root] => Array
        (
            [0] => root
            [1] => Array
                (
                    [0] => A
                    [1] => faruk
                )

        )

)

我需要:

CategoryTree Object
    (
        [root] => Array
            (
                [0] => root
                [1] => Array
                    (
                        [0] => A
                        [1] => faruk
                        [2] => Array
                            (
                                [0] => B
                            )
                    )

            )

    )

2 个答案:

答案 0 :(得分:1)

因此:

$r=$this->root;

更改或添加$ r的值不会影响$ this-&gt; root,因为它们是分开的。您需要直接访问$ this-&gt; root,或者通过引用分配$ r:

$r = &$this->root;

$parentCategory = $r[1];相同,请将其更改为:

$parentCategory = &$r[1];

答案 1 :(得分:0)

好吧,在将一段代码放入函数(getCategoryWithNameInSubtree)中的某个地方,引用将丢失。对于我的生活,我无法在功能上得到它,并且必须从身体内部的函数移动lal代码,其中这个(现在已删除的)functin被调用。调整后&amp;在这里和那里签名,我设法正确获取对数组属性的引用并为其末尾分配一个新元素