I guess, without performing one query per depth level right ? :)
If not it is just basic recursion.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I Have categories table where the category can belongs to other category and category has many categories too . and this for all categories .
example:
$categories = [
[
'name' => 'cat1',
'children' => [
[
'name' => 'cat1',
'children' => [
[
'name'=>'subcat1',
'children'=> []
]
]
]
]
]
]
@Mehdi_Souihed where do you get the children here ?
I'll go with :
function list_categories(Array $categories)
{
$data = [];
foreach($categories as $category)
{
$data[] = [
'name' = $category->name,
'children' = list_categories($category->children),
];
}
return $data;
}
$array_categories = list_categories($root_categories);
Maybe @JarekTkaczyk has a trick to eager load everything ;)
Please or to participate in this conversation.