在foreach中组合先前的数组值

时间:2013-03-07 21:21:53

标签: php foreach

我在数组中有目录,我的目标是在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

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

3 个答案:

答案 0 :(得分:5)

要获得确切的输出,您可以使用array_slice()

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

will output

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);

答案 1 :(得分:0)

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

implode( '/', $array )

请参阅http://www.php.net/manual/en/function.implode.php

答案 2 :(得分:0)

在循环中构建路径:

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