我有一张代表代理商的表格。每个机构可能有或没有父母(fk_organismo)。没有父母的机构(fk_organismo = NULL)是根代理。
任何人都可以使用 php 函数(递归与否)来构建完整的分层树,并且还可以接收可选参数:fk_organismo(parent_agency_id)。如果此参数不为NULL,则应从此特定代理开始构建树?
我还想我必须构建两(2)个单独的SQL查询,一个用于获取所有代理,另一个用于从特定的一个获取所有孩子,但不确定... < / p>
提前多多感谢
答案 0 :(得分:1)
我正在考虑这样的事情(固定,测试过)
$conn = new mysqli("hostname","user","password","database");
if($conn->connect_errno) {
printf("Connect failed: %s\n",$conn->connect_error);
exit();
}
function dbToTree(){
//Set up your connection to mysql first
global $conn;
$sql = "SELECT * FROM `database`.`table` WHERE `fk_organismo` IS NULL ORDER BY `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 the array is empty, remove it
foreach($db_array as $row => $columns){
$db_tree[$columns['nombre']]['info'] = $columns; //Tree root is ID of agency
$db_tree[$columns['nombre']]['children'] = find_children($columns['id']);
}
return $db_tree;
}
function find_children($fk_organismo){
global $conn;
$sql = "SELECT * FROM `database`.`table` WHERE `fk_organismo` = " . $fk_organismo . " ORDER BY 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 as $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;
}