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

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog