dongqian6554
dongqian6554
2018-12-23 21:07

如何从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 dongxu198714 3年前

    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;
        }
    }   
    
    点赞 评论 复制链接分享