0
cID cPID cSlug cName
1 0 hello H1
2 0 world WORLD
3 0 mars MARS
4 1 people People
5 1 dogs Dogs
6 3 cats Cats:)

cPID: Parent ID

PHP:

$getMenuData = $db->table($vtCategories)->getAll();
$menu = [];
foreach ($getMenuData as $row) {
    if ($row->cPID === 0) {
        $menu[$row->cID] = $row;
        $menu[$row->cID]['submenus'] = [];
    } else {
        $menu[$row->cPID]['submenus'][] = $row;
    }
}
foreach ($menu as $item) {
    echo $item->cID . '<br>' . PHP_EOL;    //  <<--- LINE 16
    foreach ($item['submenus'] as $subitem) {
        echo '<br>' . $subitem->cName . '--' . $subitem->cPID . PHP_EOL;
    }
}

I get this error:

Notice: Trying to get property 'cID' of non-object in /var/www/clients/client7/web31/web/test1.php on line 16

Where am I doing wrong?

1 Answers1

0

If $row is an object, you cannot do $menu[$row->cID]['submenus'], because $menu[$row->cID] is an object, not an array.

You should use $menu[$row->cID]->submenus.

Also, $row->cPID === 0 is not a good condition because if will not create the "main" entry if cPID is not 0.

You could use if (!isset($menu[$row->cID])) { to create main entry if not exist and if ($row->cPID > 0) { to add is cPID is defined.

Full code

$menu = [];
foreach ($getMenuData as $row) {
    if (!isset($menu[$row->cID])) {
        $menu[$row->cID] = $row;
        $menu[$row->cID]->submenus = [];
    } 
    if ($row->cPID > 0) {
        $menu[$row->cPID]->submenus[] = $row;
    }
}
foreach ($menu as $item) {
    
    echo $item->cID . '<br>' . PHP_EOL;    //  <<--- LINE 16
    foreach ($item->submenus as $subitem) {
        echo '<br>' . $subitem->cName . '--' . $subitem->cPID . PHP_EOL;
    }
}

Output:

1<br>
<br>People--1
<br>Dogs--1
2<br>
3<br>
<br>Cats:)--3
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • Live demo : https://3v4l.org/HEOUW – Syscall Feb 23 '22 at 17:44
  • Thank you for your help but this time I got one more error. [Screenshot](https://ibb.co/wwCpvxx). So what's wrong with my [array -> `getMenuData`](https://pastebin.com/1ZMB5XTk)? –  Feb 23 '22 at 17:51
  • I've update the answer. Please check the different `if`. And see the live demo : https://3v4l.org/oO5g9 – Syscall Feb 23 '22 at 18:07
  • Your explanation was enlightening for me. I have seen my mistake. Thank you for your time. –  Feb 23 '22 at 18:14