php - 如何使用 mysql 中的数据动态生成 php 中的嵌套数组?

标签 php mysql arrays

我试图在 php 和 mysql 中以嵌套数组的形式获得结果,但我没有得到嵌套数组,它给了我许多不同的数组。

Mysql数据:

+-----+--------+--------+-----+-----+
| 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);
    ?>

想要输出:

   array(
        food => array(
            fruit => array(
                yellow => array(banana),
                red => array(cherry)
            ),
            meat => array(beaf, pork)
        )
    );

最佳答案

尝试将 $node 作为引用参数传递给您的方法

函数display_children($parent, $level, &$node = array)

最终会得到多个数组,因为 $node 的范围是函数调用,并且每次调用函数 $node 都会重新初始化。

关于php - 如何使用 mysql 中的数据动态生成 php 中的嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36419490/

相关文章:

jquery - 在Here API(GEO FENCING)中动态传递路线路径和栅栏路径以跟踪目标

php - 如果 post_meta_value 匹配,则将新类添加到 css

php - 来自 MySQL/PHP 的 Highcharts 数据

php - 向mysql数据库插入多行

mysql - 如何在单个过程中编写多个选择查询?

mysql - 为什么我不应该为 max_connections 使用最大值

php - 无循环按键对多维数组的值求和

PHP 列数正确但仍然得到 "Column Count Doesn' t 匹配值计数在第 1 行”

php - mysql JSON_EXTRACT - 不返回任何结果

java - 使用更新的标记删除 map 上的多个标记