拥有这种群体结构
Public [id=1]
|—Registered [id=2]
|—|—Author [id=3]
|—|—|—Editor [id=4]
|—|—|—|—Publisher [id=5]
|—Manager [id=6]
|—|—Administrator [id=7]
拥有这个初始描述性数组:
Array (
[1] => Array (
[id] => 1
[descript] =>
[parent_id] => 0
[group] => Public
[parent] => 0
)
[2] => Array (
[id] => 2
[descript] =>
[parent_id] => 1
[group] => Registered
[parent] => Public
)
[3] => Array (
[id] => 3
[descript] =>
[parent_id] => 2
[group] => Author
[parent] => Registered
)
[4] => Array (
[id] => 4
[descript] =>
[parent_id] => 3
[group] => Editor
[parent] => Author
)
[5] => Array (
[id] => 5
[descript] =>
[parent_id] => 4
[group] => Publisher
[parent] => Editor
)
[6] => Array (
[id] => 6
[descript] =>
[parent_id] => 1
[group] => Manager
[parent] => Public
)
[7] => Array (
[id] => 7
[descript] =>
[parent_id] => 6
[group] => Administrator
[parent] => Manager
)
)
需要处理此数组并添加[inh]键,该键将保存键的底部路径值:
Array (
[1] => Array (
[id] => 1
[descript] =>
[parent_id] => 0
[group] => Public
[parent] => 0
[inh] => Array(0)
)
[2] => Array (
[id] => 2
[descript] =>
[parent_id] => 1
[group] => Registered
[parent] => Public
[inh] => Array(1,0)
)
[3] => Array (
[id] => 3
[descript] =>
[parent_id] => 2
[group] => Author
[parent] => Registered
[inh] => Array(2,1,0)
)
[4] => Array (
[id] => 4
[descript] =>
[parent_id] => 3
[group] => Editor
[parent] => Author
[inh] => Array(3,2,1,0)
)
[5] => Array (
[id] => 5
[descript] =>
[parent_id] => 4
[group] => Publisher
[parent] => Editor
[inh] => Array(4,3,2,1,0)
)
[6] => Array (
[id] => 6
[descript] =>
[parent_id] => 1
[group] => Manager
[parent] => Public
[inh] => Array(1,0)
)
[7] => Array (
[id] => 7
[descript] =>
[parent_id] => 6
[group] => Administrator
[parent] => Manager
[inh] => Array(6,1,0)
)
)
有关如何在不使用递归或类的情况下实现此目的的任何建议? 在最坏的情况下,我同意使用递归函数。 试图写一个递归函数但到目前为止没有成功。
答案 0 :(得分:1)
假设数组键等于id
function parentList($map, &$element){
if(!isset($element['inh'])){
if($pid = $element['parent']){
$element['inh'] = array_merge([$pid], parentList($map, $map[$pid]));
}else{
$element['inh'] = [];
}
}
return $element['inh'];
}
foreach($a as &$e){
parentList($a, $e);
}
答案 1 :(得分:0)
看起来像这样
function setAllGroupsInheritanceSQL (&$allGroups, $parent=0) {
foreach ($allGroups as $k=>$grp_arr) {
if ($grp_arr['parent_id']==$parent) {
$child=$grp_arr['id'];
if (isset($allGroups[$parent]['inh'])) $inherit_arr=$allGroups[$parent]['inh'];
$inherit_arr[]=$parent;
$allGroups[$child]['inh']=$inherit_arr;
setAllGroupsInheritanceSQL ($allGroups, $child);
}
}
}