PHP的多级树

I have one table of folders We dont know the depth of array and first I am trying to take all folder with parentid 0 and then am again calling the same function in foreach so that iterates each folder. Below is the dummy table

    Id parentid label
    -- -------- ------
    1   0        ABC
    2   1        XYZ
    3   2        ABC2
    4   0        DUMMY

I am trying to make tree with below code:

 public function getFolder($parentId = null)
 {
     if(IS_NULL($parentId)){
         $parentId = 0;
     }
     $folders = Connection::queryBuilder()->select('f.id,f.parentid,f.label')
                ->from('folders','f')
                ->where('parentid='.$parentId)->execute()->fetchAll(PDO::FETCH_OBJ);

    $temp = array();
    foreach($folders as $folder){
        $subfolders = self::getFolder($folder->id,$temp);
        array_push($temp,$folder,$subfolders);
    }

    return $temp;
}

But I am not getting the array the way I want. Can anyone help me?
Thanks in advance

There was a very close question: How to created nested multi dimensional array from database result array with parent id

#!/usr/bin/env php
<?php

// ordered by parent
$src = array(
    ['cid'=>'1','name'=>'Rootcat','parent'=>'0'],
    ['cid'=>'3','name'=>'dddd','parent'=>'1'],
    ['cid'=>'4','name'=>'test1','parent'=>'3'],
    ['cid'=>'5','name'=>'Test123 rec','parent'=>'3'],
    ['cid'=>'6','name'=>'abceg','parent'=>'3'],
    ['cid'=>'7','name'=>'JHGSGF','parent'=>'5'],
);
// inverse array, better take it sorted by parent_id desc
$data = array_reverse($src,false);
$for_parent = [];

foreach($data as $rec) {
    if (isset($for_parent[$rec['cid']])) {
        $rec['sub'] = $for_parent[$rec['cid']];
        unset($for_parent[$rec['cid']]);
    }
    $for_parent[$rec['parent']] [$rec['cid']]= $rec; 
}

print_r($for_parent);

So you can create array without recursive function.