如何根据匹配的键将此平面数组转换为多维数组?
$items = [
0 => [
'id' => 100,
'parent' => 0,
'url' => 'Home'
],
1 => [
'id' => 101,
'parent' => 0,
'url' => 'About'
],
2 => [
'id' => 102,
'parent' => 101,
'url' => 'Group'
],
3 => [
'id' => 103,
'parent' => 102,
'url' => 'Mission'
],
4 => [
'id' => 104,
'parent' => 102,
'url' => 'Vision'
],
];
我的尝试:
$new_items = array();
foreach ($items as $key => $item) {
// Store what you need.
$temp_item = array(
'id' => $item['id'],
'url' => $item['url'],
'parent_id' => $item['parent'],
'children' => array()
);
// Item does not have a parent so item_parent equals 0 (false).
if (!$item['parent']) {
// Push the item to the array.
array_push($new_items, $temp_item);
}
// Item that has a parent.
if ($item['parent']) {
// Search key by column 'id'.
$key = array_search($item['parent'], array_column($new_items, 'id'));
// Push sub item to the children array.
array_push($new_items[$key]['children'], $temp_item);
}
}
print_r($new_items);
结果:
Array
(
[0] => Array
(
[id] => 100
[url] => Home
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 103
[url] => Mission
[parent_id] => 102
[children] => Array
(
)
)
[1] => Array
(
[id] => 104
[url] => Vision
[parent_id] => 102
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 101
[url] => About
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 102
[url] => Group
[parent_id] => 101
[children] => Array
(
)
)
)
)
)
这就是我所追求的:
Array
(
[0] => Array
(
[id] => 100
[url] => Home
[parent_id] => 0
[children] => Array
(
)
)
[1] => Array
(
[id] => 101
[url] => About
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 102
[url] => Group
[parent_id] => 101
[children] => Array
(
[0] => Array
(
[id] => 103
[url] => Mission
[parent_id] => 102
[children] => Array
(
)
)
[1] => Array
(
[id] => 104
[url] => Vision
[parent_id] => 102
[children] => Array
(
)
)
)
)
)
)
)
有任何想法和建议吗?
答案 0 :(得分:2)
来自link
我已根据要求更改了功能参数 这是你的代码。
function buildTree(array $elements, $options = [
'parent_id_column_name' => 'parent',
'children_key_name' => 'children',
'id_column_name' => 'id'], $parentId = 0)
{
$branch = array();
foreach ($elements as $element) {
if ($element[$options['parent_id_column_name']] == $parentId) {
$children = buildTree($elements, $options, $element[$options['id_column_name']]);
if ($children) {
$element[$options['children_key_name']] = $children;
}else{
$element[$options['children_key_name']] = []; // added this line for empty children array
}
$branch[] = $element;
}
}
return $branch;
}
这是您的工作demo。