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)
        )
    );
1
  • you need to create another query in while loop and inner query contain $parent = "CHILD_OF_FOOD". Commented Apr 5, 2016 at 7:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.