更新时间:2023-02-14 12:38:13
我认为 PHP 中没有内置函数可以做到这一点.
I don't think there is a built-in function in PHP that does this.
我尝试了以下代码,似乎可以按照您描述的方式准备嵌套数组:
I tried the following code, and it seems to work to prepare the nested array the way you describe:
$nodes = array();
$tree = array();
foreach ($source as &$node) {
$node["Children"] = array();
$id = $node["Menu"]["id"];
$parent_id = $node["Menu"]["parent_id"];
$nodes[$id] =& $node;
if (array_key_exists($parent_id, $nodes)) {
$nodes[$parent_id]["Children"][] =& $node;
} else {
$tree[] =& $node;
}
}
var_dump($tree);
我在为演示文稿编写的 PHP 类中编写了一个类似的算法 Hierarchical Models在 SQL 和 PHP 中,但我使用的是对象而不是普通数组.
I wrote a similar algorithm in a PHP class I wrote for my presentation Hierarchical Models in SQL and PHP, but I was using objects instead of plain arrays.