这里有两个问题;为什么会这样?那可以做些什么呢?
很抱歉这个问题已经很久了,但大部分只是print_r
输出了!
基本上,我首先使用一个平面的标记数组($tags
),每个标记都包含id
(数组索引),name
和parent_id
。然后我递归迭代$tags
并将所有子标记嵌套在其父级中。 (见下文)
有效! (见下面的输出)。但我遇到的问题是我的平面数组标签是从嵌套/递归的函数中写入的。 (见下文)
平面标签数组:
Array
(
[1] => stdClass Object
(
[name] => instruments
[parent_id] => 0
)
[2] => stdClass Object
(
[name] => strings
[parent_id] => 1
)
[3] => stdClass Object
(
[name] => violin
[parent_id] => 2
)
[4] => stdClass Object
(
[name] => cello
[parent_id] => 2
)
[5] => stdClass Object
(
[name] => woodwind
[parent_id] => 1
)
[6] => stdClass Object
(
[name] => flute
[parent_id] => 5
)
)
这是嵌套子标记的递归调用函数。问题出在if
内:我将$tag
分配给$tree[$i]
,然后将children
属性添加到其中。这会导致将children
属性添加到$tag
。这就是我想要停止发生的事情。
public function tags_to_tree($tags, $parent_id = 0)
{
$tree = array();
foreach($tags as $i => $tag)
{
// add this tag node and all children (depth-first recursive)
if(intval($parent_id) === intval($tag->parent_id))
{
$tree[$i] = $tag;
$tree[$i]->children = $this->tags_to_tree($tags, $i);
}
}
return $tree;
}
嵌套标签输出:
Array
(
[1] => stdClass Object
(
[name] => instruments
[parent_id] => 0
[children] => Array
(
[2] => stdClass Object
(
[name] => strings
[parent_id] => 1
[children] => Array
(
[3] => stdClass Object
(
[name] => violin
[parent_id] => 2
)
[4] => stdClass Object
(
[name] => cello
[parent_id] => 2
)
)
)
[5] => stdClass Object
(
[name] => woodwind
[parent_id] => 1
[children] => Array
(
[6] => stdClass Object
(
[name] => flute
[parent_id] => 5
)
)
)
)
)
)
将children
属性添加到$tree[$i]
,或将$tag
分配给$tree[$i]
以阻止此情况发生时,我可以采取哪些不同的做法?
谢谢!
答案 0 :(得分:2)
平面数组是一个对象(引用)数组,即使您将对象放入一个新数组,它仍然是您移动的同一个对象。
如果您不想编辑相同的参考文献,请查看Object Cloning
即。使用:
$tree[$i] = clone $tag;