dongqian6554 2018-12-23 13:07
浏览 308
已采纳

如何从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 13: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;
        }
    }   
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部