mysql - PHP Function to build a tree starting from specific node -


i have table represents agencies. each agency may or not have parent (fk_organismo). agencies without parent (fk_organismo = null) root agencies.

table structure

could me php function (recursive or not) can build complete hierarchical tree, , can receive optional parameter: fk_organismo (parent_agency_id). if parameter not null, tree should built starting specific agency?

  1. i must show agencies in tree
  2. must show tree of children agencies starting specific one

i guess have build 2 (2) separate sql queries, 1 getting agencies, other getting children specific one, not sure...

thanks lot in advance

i'm thinking this(fixed, tested)

$conn = new mysqli("hostname","user","password","database"); if($conn->connect_errno) {     printf("connect failed: %s\n",$conn->connect_error);     exit(); }  function dbtotree(){ //set connection mysql first     global $conn;      $sql = "select * `database`.`table` `fk_organismo` null order `id` asc limit 1000;";      $result = $conn->query($sql);      for($i = 0; $db_array[$i] = $result->fetch_array(mysqli_assoc); $i++);      array_pop($db_array); //the last part of array empty, remove      foreach($db_array $row => $columns){         $db_tree[$columns['nombre']]['info'] = $columns; //tree root id of agency          $db_tree[$columns['nombre']]['children'] = find_children($columns['id']);     }     return $db_tree; }  function find_children($fk_organismo){         global $conn;         $sql = "select * `database`.`table` `fk_organismo` = " . $fk_organismo . " order id desc";         //die($sql);         $result = $conn->query($sql);         if(!$result) return null;         for($i = 0; $tmp[$i] = $result->fetch_array(mysqli_assoc); $i++);          array_pop($tmp);         foreach($tmp $tmp_row => $tmp_columns){             $return[$tmp_columns['nombre']]['info'] = $tmp_columns;             $return[$tmp_columns['nombre']]['children'] = find_children($tmp_columns['id']);         }         if(empty($return)) return null;         return $return; } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -