$array = [
[
"TITLE" => "Тест 1",
"LEVEL" => 1,
],
[
"TITLE" => "Тест 2",
"LEVEL" => 2,
],
[
"TITLE" => "Тест 3",
"LEVEL" => 2,
],
[
"TITLE" => "Тест 4",
"LEVEL" => 3,
],
[
"TITLE" => "Тест 5",
"LEVEL" => 2,
],
[
"TITLE" => "Тест 6",
"LEVEL" => 3,
],
];
$array = [
[
"TITLE" => "Тест 1",
"LEVEL" => 1,
"CHILD" => [
[
"TITLE" => "Тест 2",
"LEVEL" => 2,
],
[
"TITLE" => "Тест 3",
"LEVEL" => 2,
"CHILD" => [
"TITLE" => "Тест 4",
"LEVEL" => 3,
]
],
[
"TITLE" => "Тест 5",
"LEVEL" => 2,
"CHILD" => [
"TITLE" => "Тест 6",
"LEVEL" => 3,
]
]
]
],
];
$array = [
["TITLE" => "Тест 1", "LEVEL" => 1,],
["TITLE" => "Тест 2", "LEVEL" => 2,],
["TITLE" => "Тест 3", "LEVEL" => 2,],
["TITLE" => "Тест 4", "LEVEL" => 3,],
["TITLE" => "Тест 5", "LEVEL" => 2,],
["TITLE" => "Тест 6", "LEVEL" => 3,],
];
const TITLE = 'TITLE';
const LEVEL = 'LEVEL';
const CHILDREN = 'CHILDREN';
$result = [];
$refs = [];
foreach ($array as $item) {
$level = $item[LEVEL];
if ($level === 1) {
$result[] = $item;
$refs = [&$result[count($result) - 1]];
} else {
for ($i = count($refs) - 1; $i >= 0; $i--) {
$parent = &$refs[$i];
if ($parent[LEVEL] === $level - 1) {
if (!isset($parent[CHILDREN])) {
$parent[CHILDREN] = [];
}
$parent[CHILDREN][] = $item;
array_splice($refs, $i + 1);
$refs[] = &$parent[CHILDREN][count($parent[CHILDREN]) - 1];
unset($parent);
break;
} else {
unset($parent);
continue;
}
}
}
}
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
[
{
"TITLE": "Тест 1",
"LEVEL": 1,
"CHILDREN": [
{
"TITLE": "Тест 2",
"LEVEL": 2
},
{
"TITLE": "Тест 3",
"LEVEL": 2,
"CHILDREN": [
{
"TITLE": "Тест 4",
"LEVEL": 3
}
]
},
{
"TITLE": "Тест 5",
"LEVEL": 2,
"CHILDREN": [
{
"TITLE": "Тест 6",
"LEVEL": 3
}
]
}
]
}
]