0

I am trying to Get a result in the form of nested array in php and mysql but i am not getting nested array it gives me many different array.

Mysql data:

+-----+--------+--------+-----+-----+
| id  | parent | child  | lft | rgt |
+-----+--------+--------+-----+-----+
| 15  | red    | cherry | 4   | 5   |
| 3   | food   | fruit  | 2   | 11  |
| 32  | null   | food   | 1   | 18  |
| 543 | fruit  | yellow | 7   | 10  |
| 657 | yellow | banana | 8   | 9   |
| 66  | fruit  | red    | 2   | 6   |
| 767 | food   | meat   | 12  | 17  |
| 934 | meat   | pork   | 15  | 16  |
| 986 | meat   | beef   | 13  | 14  |
+-----+--------+--------+-----+-----+

Php:

    <?php
        @mysql_connect("localhost", "root", "");
        @mysql_select_db("kora");

        function display_children($parent, $level) {
            $result = mysql_query("SELECT child FROM downline WHERE parent='$parent'");
            $node = array();
            while ($row = mysql_fetch_array($result)) {
                $nodes = array($parent => $row['child']);
                print_r($nodes);
                display_children($row['child'], $level + 1);
            }
        }

        display_children('food', 0);
    ?>

want output:

   array(
        food => array(
            fruit => array(
                yellow => array(banana),
                red => array(cherry)
            ),
            meat => array(beaf, pork)
        )
    );
mitkosoft
  • 5,262
  • 1
  • 13
  • 31

1 Answers1

0

Try to pass $node as referenced parameter to your method

function display_children($parent, $level, &$node = array)

You end up with multiple arrays because scope of $node is to function call and every time you call function $node is reinitialized.

b3n1Am1n
  • 47
  • 4