PHP плоский массив в многомерный массив по родительским ключам?

Как я могу превратить этот плоский массив в многомерный массив в соответствии с соответствующим ключом?

$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
(
)

)
)

)

)

)

)

Есть идеи и предложения?

1

Решение

От ссылка на сайт

Я изменил параметры функции согласно требованию.
Вот твой код.

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;
}

Вот твоя работа демонстрация.

2

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]