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.
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?
- i must show agencies in tree
- 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
Post a Comment