У меня есть следующий массив:
Array
(
[0] => Array
(
[id] => 2
[title] => Root 2
[description] =>
[site_id] => 1
[parent_id] => 0
[created_at] =>
[updated_at] =>
[children] => Array
(
[0] => Array
(
[id] => 4
[title] => Child 2
[description] =>
[site_id] => 1
[parent_id] => 2
[created_at] =>
[updated_at] =>
[children] => Array
(
[0] => Array
(
[id] => 6
[title] => Child 4
[description] =>
[site_id] => 1
[parent_id] => 4
[created_at] =>
[updated_at] =>
)
)
)
)
)
[2] => Array
(
[id] => 7
[title] => Root 3
[description] =>
[site_id] => 1
[parent_id] => 0
[created_at] =>
[updated_at] =>
)
)
Я хотел бы сгладить это что-то вроде следующего:
Array
(
[0] => Array
(
[id] => 2
[title] => Root 2
[description] =>
[site_id] => 1
[parent_id] => 0
[created_at] =>
[updated_at] =>
[depth] => 0
)
[1] => Array
(
[id] => 4
[title] => Child 2
[description] =>
[site_id] => 1
[parent_id] => 2
[created_at] =>
[updated_at] =>
[depth] => 1
)
[2] => Array
(
[id] => 6
[title] => Child 4
[description] =>
[site_id] => 1
[parent_id] => 4
[created_at] =>
[updated_at] =>
[depth] => 2
)
[3] => Array
(
[id] => 7
[title] => Root 3
[description] =>
[site_id] => 1
[parent_id] => 0
[created_at] =>
[updated_at] =>
[depth] => 0
)
)
Обратите внимание на клавишу «глубина» — она должна указывать, насколько глубоко в исходном массиве был элемент
Самозвонящие / рекурсивные функции не проблема
Есть идеи?
function flatten($elements, $depth) {
$result = array();
foreach ($elements as $element) {
$element['depth'] = $depth;
if (isset($element['children'])) {
$children = $element['children'];
unset($element['children']);
} else {
$children = null;
}
$result[] = $element;
if (isset($children)) {
$result = array_merge($result, flatten($children, $depth + 1));
}
}
return $result;
}
//call it like this
flatten($tree, 0);
Других решений пока нет …