PHP分层数组 - 父母和孩子

我正在创建一个父子层次结构数组。请在数组下方找到并帮助我修复。


它parent_id在按顺序时工作正常,但我想保持我的数组值相同。


function Testing()

{

    $tasks[] = array("id" => 1, "parent_id" => 0);

    $tasks[] = array("id" => 2, "parent_id" => 5);

    $tasks[] = array("id" => 3, "parent_id" => 2);

    $tasks[] = array("id" => 5, "parent_id" => 3);

    $tasks[] = array("id" => 4, "parent_id" => 3);

    $tasks[] = array("id" => 6, "parent_id" => 5);

    $tasks[] = array("id" => 7, "parent_id" => 6);


    $tree = buildTree($tasks);

    print("<pre>");print_r($tree);

}


function buildTree(array $elements, $parentId = 0) {

    $branch = array();


    foreach ($elements as $element) {

        if ($element['parent_id'] == $parentId) {

            $children = buildTree($elements, $element['id']);

            if ($children) {

                $element['children'] = $children;

            }

            $branch[] = $element;

        }

    }


    return $branch;

}

慕斯王
浏览 94回答 1
1回答

蓝山帝景

为了避免无限循环的错误,当某些元素的子元素具有 parent_id 时,您可以使用第三个参数来列出所有已管理的 id。如果一个 id 在你的治疗中回来,你可以抛出一个异常:function buildTree(array $elements, $parentId = 0, $managedParent = []) {&nbsp; &nbsp; $branch = array();&nbsp; &nbsp; // Add new id in list of managed ids&nbsp; &nbsp; $managedParent[] =$parentId;&nbsp; &nbsp; foreach ($elements as $element) {&nbsp; &nbsp; &nbsp; &nbsp; if ($element['parent_id'] == $parentId) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // check id not already managed&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(in_array($element['id'], $managedParent))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // in this case children are already a parent of same structure. Throw an Excpetion&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new \Exception('Invalid structure given');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $children = buildTree($elements, $element['id'], $managedParent);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($children) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $element['children'] = $children;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $branch[] = $element;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $branch;}
打开App,查看更多内容
随时随地看视频慕课网APP