dongxi4235 2012-07-10 02:53
浏览 39
已采纳

增加MySQL查询的深度

public function get_children($id)
{
        $query = $this->db->query("SELECT 
          @last_id := id AS id,
          parent_id,
          FIO,
          @depth := IF(parent_id = ".$id.", 1, @depth + 1) AS depth,
          @first := IF(id = ".$id.", 'first', null) AS first
          FROM 
          users 
          FORCE INDEX (index_parent_id, PRIMARY, index_both),
          (SELECT @last_id := ".$id.", @depth := -1) vars
          WHERE id = ".$id." OR parent_id = @last_id OR parent_id = ".$id."
          ");

    return $query;

}

How can i increase the level depth of children nodes using the adjacent-model-list and this query, by now it gives me the root parent(selected by id in the function) and their children, but not deeper, any ideas?

foreach($query->result() as $q){


    if($q->first == 'first')
    {
        $parent_id = $q->parent_id;
        break;
    }


}
function print_list($array, $parent=0) {
        print "<ul>";
        foreach ($array as $row) {
            if ($row->parent_id == $parent) {
                print "<li>$row->FIO";
                print_list($array, $row->id);  # recurse
                print "</li>";
        }   }
        print "</ul>";
    }
echo print_list($query->result(), $parent_id);

then I render it in the view file...please help or any advices about what to change or see to increase the depth of the mysql query.

  • 写回答

1条回答 默认 最新

  • drexlz0623 2012-07-10 03:41
    关注

    I'm not sure about the schema of the database, but this is basically a stripped down version of something you might be looking for. Basically, you'll need a function that calls itself, but the argument changes.

    In this case, it looks for users with parent_id = $parent_id (assuming the parent_id of the root is 0) lists then, and for each of the users, it looks for other users with parent_id = $id (where $id is their id) so basically, you have infinite depth

    <?
    function print_list($parent_id) {
        $query = "SELECT * FROM users WHERE parent_id=".$parent_id;
    
        print "<ul>";
        foreach($query->result() as $q) {
            $id = $q->id;
            print "<li>";
                print $q->FIO;
            print "</li>";
            print_list($id); //Here, it calls itself again
        }
        print "</ul>";
    }
    print_list(0); //Assuming the root-parent-id number is 0
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度