转换扁平阵列到多维 [英] Convert flat array to the multi-dimentional
问题描述
我有树数据的数组(由家长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
)
)
);
有些家长从源阵列丢失。我想与父母缺少以root身份的物品。结果数组:
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.
我尝试以下code,它似乎工作,prepare嵌套数组你描述的方式:
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中我的presentation 分层模型中写道写了一个类似的算法和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屋!