您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何从该结果集中创建一个数组(嵌套的类别存储在遍历模型中的数据库中)?

如何从该结果集中创建一个数组(嵌套的类别存储在遍历模型中的数据库中)?

啊,最后有一些参考文献很方便:

<?PHP
$tree = array(
    array('Cat 1', 'depth' => 0),
    array('Cat 2', 'depth' => 1),
    array('Cat 3', 'depth' => 1),
    array('Cat 4', 'depth' => 2),
    array('Cat 5', 'depth' => 1),
    array('Cat 6', 'depth' => 2),
    array('Cat 7', 'depth' => 3),
    array('Cat 8', 'depth' => 1)
);
//same as before
$currDepth = -1;

//initilialize result
$result = array();

//create path structure for depths
$path = array();

//create 'root' node
$olditem = array('children'=> &$result);


foreach($tree as $item){
    if($item['depth'] > $currDepth){
        //remove possible old reference (old depth of other branch
        if(isset($path[$item['depth']])) unset($path[$item['depth']]);

        //make sure we have an array entry
        if(!isset($olditem['children'])) $olditem['children'] = array();

        //acquire target
        $path[$item['depth']] = &$olditem['children'];
    }
    if($item['depth'] != $currDepth) unset($olditem);
    //set correct target
    $currDepth = $item['depth'];
    //add item
    $path[$currDepth][] = &$item;
    //copy & remove reference
    $olditem = &$item;
    unset($item);
}
//always nice to clean up reference bombs:
unset($path);
unset($olditem);

var_dump($result);
?>
其他 2022/1/1 18:52:11 有347人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶