NESTED ARRAY HELP

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
cutepraba
New php-forum User
New php-forum User
Posts: 1
Joined: Fri Jun 04, 2021 8:48 pm

Fri Jun 04, 2021 9:01 pm

Table
menu_items

id | depth | title
1 | 0 | Menu 1
2 | 0 | Menu 2
3 | 1 | Menu 2.1
4 | 1 | Menu 2.2
5 | 0 | Menu 3
6 | 1 | Menu 3.1
7 | 2 | Menu 3.1.1
8 | 1 | Menu 3.2


I am building a nested bootstrap menu. I need the above in nested array.


$tree[$parent] = $tiltle;
$tree[$parent]['haschild'] = $tiltle;
----
if second level
$tree[$parent]['haschild'][2ndlevelparent][haschild] = $tiltle;
--
if third level
$tree[$parent]['haschild'][2ndlevelparent][haschild][3rdlevelparent][haschild] = $tiltle;


I tried every looping technique but cant get it.
simonbrahan
php-forum Fan User
php-forum Fan User
Posts: 137
Joined: Mon Jun 08, 2020 2:00 am
Contact:

Sun Jun 06, 2021 5:11 am

The table doesn't have any information about what child item should appear under what parent. That's the first thing you need. Something like:

Code: Select all

id | parent | title
1  | null   | Menu 1
2  | null   | Menu 2
3  |      2 | Menu 2.1
4  |      2 | Menu 2.2
5  | null   | Menu 3
6  |      5 | Menu 3.1 
7  |      6 | Menu 3.1.1
8  |      5 | Menu 3.2
I've removed the depth column as it doesn't tell you anything you can't get from the parent information, you can put that back in if you need it for something else.
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 1222
Joined: Mon Feb 22, 2016 5:52 pm

Sun Jun 06, 2021 7:20 am

Multi dimensional arrays can get complicate quickly, they take some time to get used to.

I think this is what you have asked for, but it might not be what you want / need if that makes any sense. As you rightly point out, there was no need for the count column, I'm not sure that you need a parent column.

Any how, have a play.

Code: Select all

<?php

$menuArray [] = ['Menu 1'];
$menuArray [] = ['Menu 2',
                  ['Menu item 2.1'],
                       ['Menu item 2.2']
                ];
$menuArray [] = ['Menu 3',
                  ['Menu item 3.1',
                       ['Menu item 3.1.1']
                  ],
                  ['Menu item 3.2']
                ];

echo '<pre>';
print_r($menuArray);
echo '</pre>';
Post Reply