我正在尝试构建类似以下的数组
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]
我当前的代码调用recurseLevelLoop
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']);
}
}
问题是出现的结果是子节点也在主阵列中。
array([serviceA, children:[abc]], abc, serviceB, serviceC);
我知道我可以运行检查,删除所有带有&gt;级别的元素在这个数组上0,但我的问题是:
是否有任何方法可以将迭代器放在recurseLevel中,以便我可以取消recurseLevelLoop