私はこのようなことを考えています(修正済み、テスト済み)
$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;
}