3v4l.org

run code in 300+ PHP versions simultaneously
<?php $inputArray = array ( 0 => array ( 'id_file' => '96', 'file_name' => 'Важный документ.docx', 'file_directory' => 'АК\\Документы', 'region' => 'Для работы', 'directory' => 'АК\\Документы\\Важный документ.docx', ), 1 => array ( 'id_file' => '97', 'file_name' => 'июнь_2020.docx', 'file_directory' => 'АК\\Документы', 'region' => 'Для работы', 'directory' => 'АК\\Документы\\июнь_2020.docx', ), 2 => array ( 'id_file' => '104', 'file_name' => '111222.pdf', 'file_directory' => 'АК\\Документы\\Почта', 'region' => 'Для работы', 'directory' => 'АК\\Документы\\Почта\\111222.pdf', ), 3 => array ( 'id_file' => '110', 'file_name' => '111222sss.pdf', 'file_directory' => 'АК\\Документы\\Почта', 'region' => 'Для работы', 'directory' => 'АК\\Документы\\Почта\\111222sss.pdf', ), 4 => array ( 'id_file' => '116', 'file_name' => 'asdasd1.pdf', 'file_directory' => 'АК\\Документы\\УК', 'region' => 'Для работы', 'directory' => 'АК\\Документы\\УК\\asdasd1.pdf', ), 5 => array ( 'id_file' => '128', 'file_name' => '111222sss.pdf', 'file_directory' => 'ДК\\Картинки\\УК', 'region' => 'Для отдыха', 'directory' => 'ДК\\Картинки\\УК\\111222sss.pdf', ), 6 => array ( 'id_file' => '128', 'file_name' => 'asdasd2.pdf', 'file_directory' => 'АК\\Приказы', 'region' => 'Для работы', 'directory' => 'АК\\Приказы\\asdasd2.pdf', ), ); $list = array_map(function($item){ $path = explode('\\', $item['file_directory']); array_splice($path, 1, 0, $item['region']); return array( 'id' => $item['id_file'], 'path' => $path, 'name' => $item['file_name'], ); }, $inputArray); function buildTree($items, $prefix = []) { $res = []; $visited = []; foreach($items as $item) { if (count($item['path']) < count($prefix)) continue; if (array_slice($item['path'], 0, count($prefix)) !== $prefix) continue; // echo json_encode([$prefix, $item], JSON_UNESCAPED_UNICODE), PHP_EOL; $node = []; if (count($item['path']) > count($prefix)) { $curPath = $item['path'][count($prefix)]; $nextPrefix = array_merge($prefix, [$curPath]); $strPrefix = implode('\\', $nextPrefix); if ($visited[$strPrefix] ?? false) continue; $node['type'] = 'folder'; $node['path'] = $strPrefix; $node['name'] = $curPath; $node['children'] = buildTree($items, $nextPrefix); $visited[$strPrefix] = true; } else { $node['type'] = 'file'; $node['name'] = $item['name']; } $res[] = $node; } return $res; } $tree = buildTree($list); // echo json_encode($list, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); echo json_encode($tree, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

preferences:
59.52 ms | 402 KiB | 5 Q