以不同的方式打印出一个阵列

时间:2017-10-04 19:50:48

标签: php arrays multidimensional-array

我一直在苦苦挣扎。我有一个包含文件列表和基本命名顺序的文件夹 - abc-def-xyz.php

我试图创建一个索引页面,以便在组中自动列出所有文件。所以:

abc-def-xyz.php
abc-def-xzz.php
abb-def-xyz.php

将在php索引页面中显示为:

abc
   def
      <a href="link/to/file">xyz</a>
      <a href="link/to/file">xzz</a>
abb
   def
      <a href="link/to/file">xyz</a>

我可以达到爆炸文件名并删除扩展名的地步,然后我就输了。任何建议将不胜感激。谢谢!

Array
(
    [0] => Array (this is applyOnline-alert-warning.php)
    (
        [0] => applyOnline
        [1] => alert
        [2] => warning
    )

    [1] => Array
    (
        [0] => applyOnline
        [1] => collectionOrDelivery
    )
)

1 个答案:

答案 0 :(得分:1)

使用此答案中的方法How to write getter/setter to access multi-level array by key names?

$array = array();

foreach($files as $file) {
    $temp = &$array;
    foreach(explode('-', $file) as $key) {
        $temp =& $temp[pathinfo($key, PATHINFO_FILENAME)];
    }
    $temp = $file;
}

产生一个可以使用键名的数组:

Array
(
    [abc] => Array
        (
            [def] => Array
                (
                    [xyz] => abc-def-xyz.php
                    [xzz] => abc-def-xzz.php
                )

        )

    [abb] => Array
        (
            [def] => Array
                (
                    [xyz] => abb-def-xyz.php
                )

        )

)