1

I have the sql structure

id parent_id
1     0
2     1
3     2
4     3
5     4
6     5
7     1
8     7
9     8

I want to make call all the sub child of id=1 up to nth child node using php

How can I get it. I'm struct by using php call back function.

Hasan Baig
  • 491
  • 6
  • 17
  • Take a look [here](http://stackoverflow.com/questions/12948009/finding-all-parents-in-mysql-table-with-single-query) at my question and the answer gives. Dont forget to see the schema – Muhammad Raheel Mar 05 '13 at 11:19

1 Answers1

0

By using recursion you are be able...

<?php
$arrayParent = $this->ToDatabase->("SELECT * FROM table WHERE parent_id = 0");
BuildList($arrayParent, 0);

function BuildList($arrayElements, $depth)
{
    foreach($arrayElements as $element)
    {
        echo str_repeat("&nbsp;&nbsp;", $depth) . $element["id"];
        $depth++;
        $totalUnder = $this->ToDatabase->("SELECT * FROM table 
                        WHERE parent_id = " . (int)$element["id"]);
        if(count($totalUnder) > 0)
            $depth = BuildList($totalUnder, $depth); //$totalUnder fetch to array and step deeper...

        return $depth;
    }
}
?>
Mayukh Roy
  • 1,815
  • 3
  • 19
  • 31
eL-Prova
  • 1,084
  • 11
  • 27
  • take care, it is very consuming in SQL request – MatRt Mar 05 '13 at 11:03
  • Thats correct, however, it is a possible solution. By optimize the first query you can reduce the requests by adding a count or hold a number of elements under a parent_id... – eL-Prova Mar 05 '13 at 14:37