用迭代器php实现层次结构的递归
我正在尝试构建一个如下所示的数组用迭代器php实现层次结构的递归,php,recursion,hierarchy,Php,Recursion,Hierarchy,我正在尝试构建一个如下所示的数组 array([serviceA, children:[abc]], serviceB, serviceC); //no child services from the main array once it becomes a child 根据数据: $mainAr = [ serviceA id: 1 parent: null level: 0 abc id: 2 parent: 1 level: 1 servi
array([serviceA, children:[abc]], serviceB, serviceC); //no child services from the main array once it becomes a child
根据数据:
$mainAr = [
serviceA
id: 1
parent: null
level: 0
abc
id: 2
parent: 1
level: 1
serviceB
id: 3
parent: null
level: 0
... and so on]
我当前的代码调用RecurseLevel循环
function recurseLevelLoop($mainAr){
$newAr = [];
for($i = 0; $i < count($mainAr); $i++){
$parent = $mainAr[$i];
array_push($newAr, $this->recurseLevel($mainAr, $parent));
}
return $newAr;
}
function recurseLevel($mainAr, $parent){
if($parent['serviceParent'] == null){ // check if there are any child nodes
return $parent['serviceName'];
} else {
// searches all objects if the value of $mainAr['serviceParent'] == $parent['idService']
$checkChildren = $this->SearchArray($mainAr, 'serviceParent', $parent['idService']);
//instantiate $parent['children'] array if none exists
if(!$parent['children']){$parent['children'] = [];}
array_push($parent['children'], $this->recurseLevel($mainAr, $mainAr[$checkChildren]));
//return populated parent service once the children have been resolved
return array($parent['serviceName'], 'children'=>$parent['children']);
}
}
我知道我可以运行一个检查,删除该数组中级别>0的所有元素,但我的问题是:
有没有办法把迭代器放在recurseLevel中,这样我就可以不用recurseLevelLoop了我不清楚你是如何在主数组中表示数据结构的。。。
数组中的子项:[abc]
是什么([serviceA,children:[abc]],abc,serviceB,serviceC)代码>平均值?此项可能有助于处理数据以创建层次结构:啊,这应该是输出。将查看,谢谢:只需重新读取,这是函数的当前输出,但它应该仅是数组([serviceA,children:[abc]],serviceB,serviceC)
其中子服务“abc”仅作为serviceA的子服务出现在数组中。抱歉说得不清楚。
array([serviceA, children:[abc]], abc, serviceB, serviceC);