Convert a series of parent-child relationships into a hierarchical tree?

前端 未结 11 2050
[愿得一人]
[愿得一人] 2020-11-22 07:04

I have a bunch of name-parentname pairs, that I\'d like to turn into as few heirarchical tree structures as possible. So for example, these could be the pairings:

         


        
11条回答
  •  轮回少年
    2020-11-22 07:34

    Parent-child relationship nested Array
    Fetch all the record from the database and creating nested array.

    $data = SampleTable::find()->all();
    $tree = buildTree($data);
    print_r($tree);
    
    public function buildTree(array $elements, $parentId = 0) {
        $branch = array();
        foreach ($elements as $element) {
            if ($element['iParentId'] == $parentId) {
                $children =buildTree($elements, $element['iCategoriesId']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }
    

    Print Categories and Sub-categories data in json Format

    public static function buildTree(array $elements, $parentId = 0){
        $branch = array();
        foreach($elements as $element){
            if($element['iParentId']==$parentId){
                $children =buildTree($elements, $element['iCategoriesId']);
                if ($children) {
                    $element['children'] = $children;
    
                }
                    $branch[] = array(
                        'iCategoriesId' => $element->iCategoriesId,
                        'iParentId'=>$element->iParentId,
                        'vCategoriesName'=>$element->vCategoriesName,
                        'children'=>$element->children,
                );
            }
        }
        return[
            $branch
        ];
    }
    

提交回复
热议问题