Php 为什么推送数组没有持久化?
我试图用线性路径构建嵌套树, 我的路径是从父级到子级排序的,如下所示:Php 为什么推送数组没有持久化?,php,Php,我试图用线性路径构建嵌套树, 我的路径是从父级到子级排序的,如下所示: $paths= array(array(999, 10, 9, 8, 7), array(999, 10, 9, 82, 75), array(999, 10, 9, 83, 74)); 其中10是999岁的孩子,9是10岁的孩子,8是9岁的孩子,以此类推 树的根具有999 id,它将显示树的顶部节点 $tree_root = array('id' => 999, 'nodes' => array()); 我
$paths= array(array(999, 10, 9, 8, 7), array(999, 10, 9, 82, 75), array(999, 10, 9, 83, 74));
其中10是999岁的孩子,9是10岁的孩子,8是9岁的孩子,以此类推
树的根具有999 id,它将显示树的顶部节点
$tree_root = array('id' => 999, 'nodes' => array());
我遇到的问题是,buildTree
不会将持久化的新子节点添加到tree\u root
中,插入只在tree\u root直接子节点中起作用,从buildTree函数返回后,tree\u root子节点中插入的任何节点都不会出现,你知道如何保留引用并解决这个问题吗
// loop of sorted paths:
for ($i = 0; $i < count($paths); $i++) {
for ($l = 0; $l < count($paths[$i]) - 1; $l++) {
$this->buildTree($tree_root, $paths[$i][$l], $paths[$i][$l + 1]);
}
}
public function buildTree(&$a, $parent_id, $child_id)
{
if ($a["id"] == $parent_id) {
$exists = false;
for ($i = 0; $i < count($a["nodes"]); $i++) {
if ($a["nodes"][$i]["id"] == $child_id) {
$exists = true;
break;
}
}
if (!$exists) {
$node_template_children = array();
$node_template = array('id' => $child_id, 'nodes' => &$node_template_children);
$node_template = &$node_template;
$a_nodes = &$a["nodes"];
// $a_nodes is not affected when returning from buildTree!!
array_push($a_nodes, $node_template);
}
return true;
}
foreach ($a["nodes"] as $node) {
$result = $this->buildTree($node, $parent_id, $child_id);
if ($result == true) {
return true;
}
}
return false;
}
//已排序路径的循环:
对于($i=0;$ibuildTree($tree\u root,$path[$i][$l],$path[$i][$l+1]);
}
}
公共函数构建树(&$a、$parent\u id、$child\u id)
{
如果($a[“id”]==$parent\u id){
$exists=false;
对于($i=0;$i$child\u id,'nodes'=>&$node\u template\u children);
$node_template=&$node_template;
$a_nodes=&$a[“nodes”];
//从buildTree返回时,$a_节点不受影响!!
数组\u推送($a\u节点,$node\u模板);
}
返回true;
}
foreach($a[“nodes”]作为$node){
$result=$this->buildTree($node、$parent\u id、$child\u id);
如果($result==true){
返回true;
}
}
返回false;
}
如果您能为我们提供一种可复制的方法来测试您的方法,那将很有帮助。。。你可以编辑你的帖子来做这件事。我已经复制了$PATH变量,请检查上面,其他代码已经被复制和粘贴了。我怀疑你忽略了一个事实,即foreach
也只在数组的副本上工作,除非你在那里明确使用引用foreach($a['nodes']as&$node)
…@deceze谢谢!你让我开心:)