dongqian6554 2018-12-23 21:07
浏览 303
已采纳

如何从php中的树状数据结构中获取最后一级元素?

My recursive function returns all the children of menu but I want to have just the last children of array, here is my code:

function test($pid){
    $arr = array();
    $sql = "SELECT * FROM wp_term_taxonomy WHERE parent=$pid && taxonomy='product_cat'";
    $result = mysqli_query($GLOBALS['conn'], $sql);

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $term_taxonomy_id = $row['term_taxonomy_id'];   
            $arr[$row['term_taxonomy_id']] = test($row['term_taxonomy_id']);
        }
    }
    return $arr;
}   

Current output:

{"26":{"194":[],"195":[],"196":[],"197":[],"198":[],"199":[],"200":[]},"30":{"201":[],"202":[],"203":[],"204":[],"205":[],"206":[],"207":[]},"32":{"217":[],"218":[],"219":[],"220":[],"221":[],"222":[],"223":[],"224":[],"225":[]},"35":{"208":[],"209":[],"210":[],"211":[],"212":[],"213":[],"214":[],"215":[],"216":[]},"38":{"226":[],"227":[],"228":[],"229":[],"230":[],"231":[],"232":[],"233":[],"234":[],"235":[],"236":[],"237":[]},"41":{"238":[],"239":[],"240":[]},"43":{"241":[],"242":[],"243":[],"244":[],"245":[],"246":[],"247":[]},"45":{"248":[],"249":[],"250":[],"251":[],"252":[],"253":[],"254":[],"255":[],"256":[]},"47":{"257":[]}}

Expected output:

{"194","195","196","197","198","199","200","201,"202","203","204","205","206","207","217","218","219","220","221","222","223","224","225","208","209","210","211","212","213","214","215","216","226","227","228","229","230","231","232","233","234","235","236","237","238","239","240","241","242","243","244","245","246","247","248","249","250","251","252","253","254","255","256","257"}
  • 写回答

1条回答 默认 最新

  • dongxu198714 2018-12-23 21:25
    关注

    Your code is pretty close - all you need to do is return stop condition to the function (no children in your case) and if not continue with the recursive calls.

    You can just add pid in case he has no children and if he has just merge all his children:

    function getLeafs($pid){
        $sql = "SELECT * FROM wp_term_taxonomy WHERE parent=$pid && taxonomy='product_cat'";
        $result = mysqli_query($GLOBALS['conn'], $sql);
    
        if (mysqli_num_rows($result) == 0) {
            return array($pid); // no children for this pid
        } else {
            $leafs = array();
            while ($row = mysqli_fetch_assoc($result)) {
                $leafs = array_merge($leafs, getLeafs($row['term_taxonomy_id']));
            }
            return $leafs;
        }
    }   
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作