У меня есть проект в php, над которым я работаю, где я беру плоский массив и делаю его вложенным массивом. Результат работает, но слишком медленно, когда мое дерево становится больше. Я просто не знаю, почему это так медленно или что делать.
$this->tree = [
[ 'id' => 1, 'parent_id' => null ],
[ 'id' => 2, 'parent_id' => 1 ],
[ 'id' => 3, 'parent_id' => 1 ],
[ 'id' => 4, 'parent_id' => 3 ],
[ 'id' => 5, 'parent_id' => 4 ],
];
// expected result
// [ 'id' => 1, 'parent_id' => null, 'children' => [
// [ 'id' => 2, 'parent_id' => 1, 'children' => [] ],
// [ 'id' => 3, 'parent_id' => 1, 'children' => [
// [ 'id' => 4, 'parent_id' => 3, 'children' => [
// [ 'id' => 5, 'parent_id' => 4, 'children' => [] ],
// ] ],
// ] ],
// ] ];
public function make_tree_nested( $base = null ) {
if ( is_null( $base ) ) {
$base = $this->get_base( $this->tree );
if ( is_null( $base ) ) return null;
}
$base['children'] = array_map(
function( $child ) {
return $this->make_tree_nested( $child );
},
$this->get_children( $base )
);
return $base;
}
private function get_base( $tree ) {
foreach( $tree as $group ) {
if ( is_null( $group['parent_id'] ) ) {
return $group;
}
}
return null;
}
private function get_children( $parent ) {
return array_values( array_filter(
$this->tree,
function( $group ) use ( $parent ) {
return $group['parent_id'] === $parent['id'];
}
) );
}