0

I am trying to build a dynamic Menu from data I generate from jstree. Jstree values will stored in database as follows:
Id | Name | Parent | Icon | Link

So I've made a method to read each row from database(propel) and store it in array, so Smarty can build a menu dynamically.

That's my function:

$menu_content = array();
    foreach($result as $key => $r) {
        if($r['Id'] != 1) {
            $Id = $r['Id'];
            $menu_content[$r['Id']] = array(
                "name" => $r['Name'],
                "link" => $r['Link'],
                "icon" => $r['Icon']
            );
            unset($result[$key]);
            foreach($result as $key_children => $c) {
                if($c['Parent'] == $r['Id']) {
                    $menu_content[$r['Id']]['children'][] = array(
                        "name" => $c['Name'],
                        "link" => $c['Link'],
                        "icon" => $c['Icon']
                    );
                    unset($result[$key_children]);
                    $Idc = $c['Id'];
                    foreach($result as $key_grandchild => $cc) {
                        if($cc['Parent'] == $c['Id']) {
                            $menu_content[$r['Id']]['children']['grandchild'][] = array(
                                "name" => $cc['Name'],
                                "link" => $cc['Link'],
                                "icon" => $cc['Icon']
                            );
                            unset($result[$key_grandchild]);
                        }
                    }
                }  
            }
        }

So it should store values like this: $menu_content[parent][children][grandchildren]. This part of code is working fine, but it's not unsetting the children and grandchildren values, so I get them twiche. First time in correct order and after that as parent children.

Thanks in advance.

spyro95
  • 136
  • 9
  • 1
    https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work/14854568#14854568, you want to change the array in the iteration body so use `&`. – cske Oct 29 '18 at 19:48
  • Thank you for replying that fast. Could you give me a short example? Thanks in advance. – spyro95 Oct 29 '18 at 19:53
  • just replace ` => $(r|c|cc)` with `=> &$(r|c|cc)` in each `foreach`, but it's bad style so try to find a better solution – cske Oct 29 '18 at 20:00
  • Thank you. I've tried your solution and it's working. But I still don't get why my code is not working properly. – spyro95 Oct 29 '18 at 20:12
  • please read and unserstand linked so answer – cske Oct 29 '18 at 20:19

0 Answers0