如何在php中将目录路径转换为数组

时间:2014-06-20 18:06:37

标签: php arrays

我有一个类似的目录结构路径 root / path1 / path2 / path3 我希望这是

Array(
[0] => "root"
[1] => Array
    (
        [0] => "path1"
        [1] => Array
            (
                [0] => "path2"
                [1] => Array
                    (
                        [0] => "path3"
                    )

            )

    )
)

1 个答案:

答案 0 :(得分:7)

试试:

$input  = 'root/path1/path2/path3';
$output = null;

foreach (array_reverse(explode('/', $input)) as $part) {
    $output = $output ? array($part, $output) : array($part);
}

var_dump($output);

输出:

array (size=2)
  0 => string 'root' (length=4)
  1 => 
    array (size=2)
      0 => string 'path1' (length=5)
      1 => 
        array (size=2)
          0 => string 'path2' (length=5)
          1 => 
            array (size=1)
              0 => string 'path3' (length=5)