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条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP