爲了實現這一點,您需要使用遞歸函數。像這樣的東西(爲我的作品):
// Get the list of files somehow (I assume you already have that):
$list_of_files = array(
'/Unit 10/Lesson 1.jpg',
'/Unit 10/Lesson 2.jpg',
'/Unit 10/Lesson 3/Homework.jpg',
'/Unit 10/Lesson 4.jpg',
'/Unit 10/Lesson 5/5.jpg',
'/Unit 10/Lesson 5/6.jpg',
'/Unit 10/Lesson 5/7.jpg',
'/Unit 10/Lesson 5/Homework/11.jpg',
'/Unit 10/Lesson 5/Homework/A.jpg',
'/Unit 10/Lesson 5/Homework/B.jpg',
'/Unit 10/Lesson 5/Homework/C.jpg',
'/Unit 10/Lesson 5/Homework/E.jpg',
'/Unit 10/Lesson 6/Workbook/3/1.jpg',
'/Unit 10/Lesson 6/Workbook/3/2.jpg',
'/Unit 10/Lesson 6/Workbook/3/3.jpg',
);
function build_array_recursive(&$array_to_insert_into, $path_string, $file_url)
{
// Break the path string into an array of maximum 2 elements using the '/' delimiter:
$path_arr = explode('/', $path_string, 2);
// If you have 2 elements, the first one will be a folder:
if (count($path_arr) == 2)
{
// Check if the folder's array already exists, create it if not:
if (!isset($array_to_insert_into[$path_arr[0]]))
{
$array_to_insert_into[$path_arr[0]] = array();
}
// Call the same function to go one level deeper in your nested array:
build_array_recursive($array_to_insert_into[$path_arr[0]], $path_arr[1], $file_url);
}
// If there's only one element that means you've reached the end of the string, and all you have left is the filename. Simply push it into the parent array:
elseif (count($path_arr) == 1)
{
$array_to_insert_into[] = $path_arr[0];
}
}
// This will be your final nested array:
$nested_array = array();
// Iterate over the file paths:
foreach($list_of_files as $path_string)
{
// Remove the first '/' from the beginning of the string, if exists (this is to avoid having an array with an empty key on the first level:
if ($path_string[0] == '/')
{
$path_string = substr($path_string, 1);
}
// Call recursive function to build the nested array:
build_array_recursive($nested_array, $path_string, $path_string);
來顯示陣列作爲一個菜單,你需要另一個遞歸函數建立嵌套的UL /李HTML標籤和顯示的鏈接文件:
function build_menu($nested_array)
{
echo '<ul>';
foreach($nested_array as $folder_name => $array)
{
echo '<li>';
if (is_array($array))
{
echo '<b>' . $folder_name . '</b><br>';
build_menu($array);
}
else
{
// get the file name out of the url (so you don't show the full url:
$path_parts = explode('/', $array);
echo '<a href="' . $array . '">' . array_pop($path_parts) . '</a>';
}
echo '</li>';
}
echo '</ul>';
}
build_menu($nested_array);
您是否嘗試使用.jpgs作爲菜單圖像?他們是否鏈接到圖像?你有什麼嘗試? –
是的,它們是圖像的鏈接,插入到「href」屬性中。 我試過 * foreach每一行,但無法創建遞歸函數 * foreach每一行,爆炸它並附加到ul如果行嵌套 – user3043178