将平面数组转换为多维 [英] Convert flat array to the multi-dimensional
问题描述
我有一个带有树数据的数组(按父ID).我想将其转换为多维数组.做到这一点的最佳方法是什么?有任何简短功能吗?
I have an array with tree data (by parent id). I want to convert it to multidimensional array. What is the best way to achieve that? Is there any short function for that?
源数组:
$source = array(
'0' => array(
'Menu' => array(
'id' => 45
'name' => 'Home'
'parent_id' => 1
)
)
'1' => array(
'Menu' => array(
'id' => 47
'name' => 'Get started'
'parent_id' => 1
)
)
'2' => array(
'Menu' => array(
'id' => 72
'name' => 'Attributes'
'parent_id' => 71
)
)
'3' => array(
'Menu' => array(
'id' => 73
'name' => 'Headings'
'parent_id' => 71
)
)
'4' => array(
'Menu' => array(
'id' => 75
'name' => 'Links'
'parent_id' => 71
)
)
'5' => array(
'Menu' => array(
'id' => 59
'name' => 'Images'
'parent_id' => 75
)
)
'6' => array(
'Menu' => array(
'id' => 65
'name' => 'Lists'
'parent_id' => 75
)
)
);
源数组中缺少某些父母.我希望缺少父项的项成为根.结果数组:
Some parents are missing from the source array. I would like the items with missing parent to be root. Result array:
$result = array(
'0' => array(
'Menu' => array(
'id' => 45
'name' => 'Home'
'parent_id' => 1
)
'Children' => array()
)
'1' => array(
'Menu' => array(
'id' => 47
'name' => 'Get started'
'parent_id' => 1
)
'Children' => array()
)
'2' => array(
'Menu' => array(
'id' => 72
'name' => 'Attributes'
'parent_id' => 71
)
'Children' => array()
)
'3' => array(
'Menu' => array(
'id' => 73
'name' => 'Headings'
'parent_id' => 71
)
'Children' => array()
)
'4' => array(
'Menu' => array(
'id' => 75
'name' => 'Links'
'parent_id' => 71
)
'Children' => array(
'0' => array(
'Menu' => array(
'id' => 59
'name' => 'Images'
'parent_id' => 75
)
'Children' => array()
)
'1' => array(
'Menu' => array(
'id' => 65
'name' => 'Lists'
'parent_id' => 75
)
'Children' => array()
)
)
)
);
更新:删除了方括号.
推荐答案
我认为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类中编写了类似的算法分层模型在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.
这篇关于将平面数组转换为多维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!