-1

我在数组中有目录,我的目标是在 foreach(或等效)语句中获取文件夹名称和文件夹路径。

这是我到目前为止所拥有的。

<?
$array = array("folder","path","here");
foreach ($array as $value){
    echo "File Name: $value";
    echo "File Path:       ";
}

如您所见,我不知道如何获取路径。我想要的,是这样的。

File Name: folder
File Path: /folder

File Name: path
File Path: /folder/path

File Name: here
File Path: /folder/path/here

有人有什么建议吗?谢谢!

4

3 回答 3

5

对于您的确切输出,您可以使用array_slice()

foreach ($array as $current_index => $value){
    echo "File Name: $value";
    echo "File Path: /" . implode( '/', array_slice( $array, 0, $current_index + 1));
}

将输出

File Name: folder
File Path: /folder

File Name: path
File Path: /folder/path

File Name: here
File Path: /folder/path/here

否则,对于完整路径,您可以使用implode()

echo implode( '/', $array);
于 2013-03-07T21:24:16.957 回答
0

使用implode函数来组合数组的元素:

implode( '/', $array )

http://www.php.net/manual/en/function.implode.php

于 2013-03-07T21:24:24.500 回答
0

在循环内构建路径:

<?
$array = array("folder","path","here");
$path = "";
foreach ($array as $value){
    $path .= "/$value";
    echo "File Name: $value";
    echo "File Path: $path";
}
于 2013-03-07T21:30:04.263 回答