dongpu1881 2013-01-16 21:10
浏览 66
已采纳

PHP递归导航

So i have this issue regarding recursive arrays. What i want is to get an recursive array with PHP from my database so that i can create a navigation menu with submenu's without creating another table.

this is the function i have so far;

function getMenu($tree = null){
        $tree2 = array();
        $tree = getPages();
        foreach($tree as $i => $item){
            if($item->parent_id == $item->ID){
                $tree2[$item->ID] = $item;
                $tree2[$item->ID]['submenu'] = getMenu($tree, $item->ID);
            }
        }

        return $tree2;
    }

To make things clear i did not create this function myself but got it from http://www.jugbit.com/php/php-recursive-menu-with-1-query/ and made adjustments where i thought where the right one

The $tree variable is coming from this function;

function getPages($limit = null,$sort = null) {
     global $db;
     $query = $db->prepare('SELECT * FROM pages ORDER BY Position');
     $query->execute();
     return $query->fetchAll(PDO::FETCH_CLASS);
}

Now i have been busting my balls over this for the last two days trying to figure out what i am doing wrong.

if i print the getMenu function all i get is an empty array wich i can't figure out why. it does get the foreach right and i don't think that's the issue but i'm not 100% sure..

i hope the question is clear but if it's not i'm sorry and will clarify where needed.

Thanks in advance

  • 写回答

2条回答 默认 最新

  • doujiang1993 2013-01-16 21:17
    关注

    In getPages, if you want it to return an associative array, then you need to do:

    return $query->fetchAll(PDO::FETCH_ASSOC);
    

    and then your getMenu would look like:

    function getMenu($tree = null, $parent = 0) {
        if (!isset($tree))
            $tree = getPages();
    
        $tree2 = array();
        foreach($tree as $i => $item) {
            if($item['id'] == $parent) {
                $tree2[$item['id']] = $item;
                $tree2[$item['id']]['submenu'] = getMenu($tree, $item['id']);
            }
        }
    
        return $tree2;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3