递归函数复制结果

时间:2019-05-26 23:54:28

标签: php recursion

如果我要重复的话请原谅。我是这里的新手,现有的答案都不能解决我的问题。我有一张桌子:

++++++++++++++++++++++++++++++++
|id       |name     |parent_id |
++++++++++++++++++++++++++++++++
|1        |Site A   |NULL      |
++++++++++++++++++++++++++++++++
|2        |Site A 1 | 1        |
++++++++++++++++++++++++++++++++
|3        |Site B   | 1        |
++++++++++++++++++++++++++++++++
|4        | Site C  | NULL     |
++++++++++++++++++++++++++++++++

我想要一个这样的树视图:

 Site A
      |Site B
      |Site A 1
 Site C

我有这个功能:

function recurseChildren(stdClass & $grp, int $iteration = 0) {
    global $db;

    if (!is_null($grp - > parent_id)) {
        $parent = $db - > query("SELECT  callpoint_groups.* FROM callpoint_groups WHERE id={$grp->parent_id}");
        if ($iteration === 0) {
            $children = $db - > query("SELECT  callpoint_groups.* FROM callpoint_groups WHERE parent_id={$grp->parent_id}");
            while ($child = $children - > fetch_object()) {
                $grp - > nodes[] = $child;

            }
        }

        $devgrp = $parent - > fetch_object();
        if ($devgrp - > parent_id) {

            #
            $devgrp - > nodes[] = $grp;#
            $grp = $devgrp;
            $devgrp - > nodes[] = recurseChildren($devgrp, ++$iteration);

        } else {
            $devgrp - > nodes[] = $grp;
            $grp = $devgrp;

        }
    }

    return $grp;
}

这将产生:

Site A
      Site A1
          Site A1
          Site B

 Site A
      Site A1
          Site A1
          Site B
 Site C
 Site C 

代替上述结果。 我该怎么做才能消除重复项。请纵容我。我是递归的新手

更新 递归函数在这里被称为

$db = new Mysqli('localhost',$user,$pass,'patakeja');

    $res = $db->query('SELECT DISTINCT callpoint_groups.* FROM callpoint_groups LEFT JOIN callpoints ON callpoint_groups.id=callpoints.callpoint_group_id WHERE callpoints.site_id=1');
    $res = $res->fetch_all(MYSQLI_ASSOC);
    $arr = array();
    while ( $data =  array_shift($res))
    {
        $data = (object)$data;
        recurseChildren($data);

        $arr[] = $data;
    }

    var_dump($arr);

0 个答案:

没有答案