我试图在 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/