任何人都可以帮我解决循环遍历递归数组和使用php创建多级嵌套列表的逻辑。我在超越顶级列表节点方面并不是很成功。
请参阅下面的数组:
Dump => array(6) {
[0] => array(5) {
["id"] => string(1) "1"
["label"] => string(13) "address types"
["slug"] => string(17) "admin/addresstype"
["parent_id"] => string(1) "0"
["has_children"] => bool(false)
}
[1] => array(5) {
["id"] => string(1) "3"
["label"] => string(9) "dashboard"
["slug"] => string(15) "admin/dashboard"
["parent_id"] => string(1) "0"
["has_children"] => bool(false)
}
[2] => array(6) {
["id"] => string(1) "5"
["label"] => string(16) "feature category"
["slug"] => string(21) "admin/featurecategory"
["parent_id"] => string(1) "0"
["has_children"] => bool(true)
["children"] => array(2) {
[0] => array(6) {
["id"] => string(1) "4"
["label"] => string(7) "feature"
["slug"] => string(13) "admin/feature"
["parent_id"] => string(1) "5"
["has_children"] => bool(true)
["children"] => array(2) {
[0] => array(5) {
["id"] => string(1) "2"
["label"] => string(6) "status"
["slug"] => string(12) "admin/status"
["parent_id"] => string(1) "4"
["has_children"] => bool(false)
}
[1] => array(5) {
["id"] => string(1) "7"
["label"] => string(4) "menu"
["slug"] => string(10) "admin/menu"
["parent_id"] => string(1) "4"
["has_children"] => bool(false)
}
}
}
[1] => array(5) {
["id"] => string(1) "9"
["label"] => string(17) "subscription type"
["slug"] => string(22) "admin/subscriptiontype"
["parent_id"] => string(1) "5"
["has_children"] => bool(false)
}
}
}
[3] => array(5) {
["id"] => string(1) "6"
["label"] => string(8) "industry"
["slug"] => string(14) "admin/industry"
["parent_id"] => string(1) "0"
["has_children"] => bool(false)
}
[4] => array(5) {
["id"] => string(1) "8"
["label"] => string(12) "subscription"
["slug"] => string(18) "admin/subscription"
["parent_id"] => string(1) "0"
["has_children"] => bool(false)
}
[5] => array(5) {
["id"] => string(2) "10"
["label"] => string(4) "user"
["slug"] => string(10) "admin/user"
["parent_id"] => string(1) "0"
["has_children"] => bool(false)
}
}
非常感谢提前
答案 0 :(得分:6)
你可以使用这样的东西
/*
* Builds a tree based on parent child relationships
* @data: relationship data
* @parent: level to start at
*/
function buildTree(Array $data, $parent = 0) {
$tree = array();
foreach ($data as $d) {
if ($d['ParentID'] == $parent) {
$children = buildTree($data, $d['id']);
// set a trivial key
if (!empty($children)) {
$d['_children'] = $children;
}
$tree[] = $d;
}
}
return $tree;
}
function printTree(Array $data, $markup = ''){
foreach($data as $elm){
echo '<li data-id="'.$elm['TrainingID'].'">'.$elm['trainingName'].'<a href="#pages|admin|training?parent='.$elm['TrainingID'].'"><span class="addChild" title="Add a child training"></span></a><span class="editTraining" title="Edit"></span>';
if(isset($elm['_children']))
{
echo '<ul>';
printTree($elm['_children'], $markup);
echo '</ul>';
}
print '</li>';
}
}