Array(
[9] => Array(
[id] => 9
[content] => 4
[pos] => 0
[fname] => pack
[playlist] => Array()
)
[11] => Array(
[id] => 11
[content] => 4
[pos] => 9
[fname] => LOL
[folder] => pack
[folderID] => Array(
[0] => 9
)
)
[13] => Array(
[id] => 13
[content] => 4
[pos] => 11
[fname] => MAZ
[folder] => pack:LOL
[folderID] => Array(
[0] => 9
[1] => 11
)
[playlist] => Array()
)
)
Array(
[9] => Array(
[id] => 9
[content] => 4
[pos] => 0
[fname] => pack
[playlist] => Array(
[11] => Array(
[id] => 11
[content] => 4
[pos] => 9
[fname] => LOL
[folder] => pack
[folderID] => Array(
[0] => 9
)
[playlist] => Array(
[13] => Array(
[id] => 13
[content] => 4
[pos] => 11
[fname] => MAZ
[folder] => pack:LOL
[folderID] => Array(
[0] => 9
[1] => 11
)
[playlist] => Array()
)
)
)
)
)
)
function rebuild(array $array) {
$count_children = [];
$without_children = [];
foreach ($array as $id => $element) {
// инициализация подсчета дочерних элементов, если это еще не было сделано
if (!isset($count_children[$id])) {
$count_children[$id] = 0;
}
if ($count_children[$id] === 0) {
$without_children[] = $id;
}
if ($element['pos'] === 0) {
continue;
}
// инкремент кол-ва дочерних элементов для родительского эл-та
if ( !isset($count_children[$element['pos']]) ) {
$count_children[$element['pos']] = 0;
}
$count_children[$element['pos']]++;
// удаление родительского эл-та из списка "бездочерних" элементов
if (($key = array_search($element['pos'], $without_children)) !== false) {
unset($without_children[$key]);
}
}
while(!empty($without_children)) {
foreach ($without_children as $key => $id) {
$parent_id = $array[$id]['pos'];
if ($parent_id !== 0) {
if (!isset($array[ $parent_id ]['playlist'])) {
$array[ $parent_id ]['playlist'] = [];
}
$array[$parent_id]['playlist'][] = $array[$id];
unset($array[$id]);
$count_children[$parent_id]--;
if ($count_children[$parent_id] <= 0 && $parent_id !== 0) {
$without_children[] = $parent_id;
}
}
unset($without_children[$key]);
}
}
return $array;
}