我有一个文件夹表 我们不知道数组的深度,我首先尝试使用parentid 0的所有文件夹,然后再次调用foreach中的相同函数,以便迭代每个文件夹。下面是虚拟表
Id parentid label
-- -------- ------
1 0 ABC
2 1 XYZ
3 2 ABC2
4 0 DUMMY
我正在尝试使用以下代码制作树:
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;
}
但我没有按照我想要的方式获得阵列。任何人都可以帮助我吗? 提前致谢
答案 0 :(得分:1)
有一个非常接近的问题: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);
所以你可以创建没有递归函数的数组。