Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Удаленная работа для IT-специалистов
<?php # дан массив директорий $folders = [ (object) ['id' => 1, 'parent' => 0, 'name' => 'foo'], (object) ['id' => 2, 'parent' => 1, 'name' => 'bar'] ]; # получить нужно /foo/bar # количество вложенных директорий неизвестно ?>
foreach ($folders as $path) { $fullpath = implode(DIRECTORY_SEPARATOR, array_keys($path)); }
$folders = [ (object) ['id' => 1, 'parent' => 0, 'name' => 'foo'], (object) ['id' => 2, 'parent' => 1, 'name' => 'bar'] ]; var_dump(folderpath($folders)); function folderpath(&$folders, $parent = 0) { $path = []; foreach ($folders as $id => $data) { if ($data->parent == $parent) { $path[] = $data->name; $sub = folderpath($folders, $data->id); if (strlen($sub) > 0) { $path[] = $sub; } } } return implode(DIRECTORY_SEPARATOR, $path); }
$folders = [ (object) ['id' => 1, 'parent' => 0, 'name' => 'foo'], (object) ['id' => 2, 'parent' => 1, 'name' => 'bar'], (object) ['id' => 3, 'parent' => 0, 'name' => 'foo2'], (object) ['id' => 4, 'parent' => 3, 'name' => 'bar2'] ]; var_dump(folderpath($folders)); function folderpath($folders) { $out = []; foreach ($folders as $id => $data) { $path = []; if ($data->parent == $parent) { $path[] = $data->name; $sub = folderpathrec($folders, $data->id); if (strlen($sub) > 0) { $path[] = $sub; } } if (count($path) > 0) { $out[] = implode(DIRECTORY_SEPARATOR, $path); } } return $out; } function folderpathrec($folders, $parent = 0) { $path = []; foreach ($folders as $id => $data) { if ($data->parent == $parent) { $path[] = $data->name; $sub = folderpathrec($folders, $data->id); if (strlen($sub) > 0) { $path[] = $sub; } } } return implode(DIRECTORY_SEPARATOR, $path); }