【问题标题】:Give unique class to list item in php array为 php 数组中的列表项提供唯一的类
【发布时间】:2013-04-08 11:43:53
【问题描述】:

我创建了一个数组,显示一个目录(本质上是目录树)的几个子目录中的所有文件。这些文件是单击时在该目录中打开文件的所有链接。

我遇到的问题是我希望能够设置我的结果的样式,但是所有子目录和文件名都具有相同的类(因为它们是使用相同的代码生成的)。

这是我的 php:

<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
echo '<ol class="song">';
foreach($ffs as $ff){
    if($ff != '.' && $ff != '..'){
        echo '<li class="title">';
        if(is_dir($dir.'/'.$ff)){
            echo $ff;
            listFolderFiles($dir.'/'.$ff);
        }else{
            echo '<a href="'.$dir.'/'.$ff.'" target="_blank">'.$ff.'</a>';
        }
        echo '</li>';
    }
}
echo '</ol>';
}

listFolderFiles('Current Songs');

?>

而生成的html是这样的:

<ol class="song">
<li class="title">
  Sub Directory Folder 1
<ol class="song">
    <li class="title">
    <a href="Current Songs/Song1.mp3"></a></li>
    <li class="title">
    <a href="Current Songs/Song1.pdf"></a></li>
</ol>
</li>
<li class="title">
  Sub Directory Folder 2
<ol class="song">
    <li class="title">
    <a href="Current Songs/Song2.mp3"></a></li>
    <li class="title">
    <a href="Current Songs/Song2.pdf"></a></li>
</ol class="song">
</li>

</ol>
</li>

如您所见,每个条目由 2 个有序列表组成,但它们都具有相同的类,所有列表项也是如此,这使得几乎不可能对其进行任何样式设置。

我想要的是生成以下 html 标记:

<ol class="song">
<li class="title">
  Sub Directory Folder 1
</li> <!--END TITLE HERE-->
<ol>
    <li>
    <a href="Current Songs/Song1.mp3"></a></li>
    <li>
    <a href="Current Songs/Song1.pdf"></a></li>
</ol>
</ol> <!--END SONG OL HERE-->

任何人都可以就我需要对我的代码进行哪些 php 更改以输出上述内容提供一些建议。

【问题讨论】:

    标签: php arrays list listitem


    【解决方案1】:

    你也可以将类名作为参数传递

    function listFolderFiles($dir,$myclass){
    $ffs = scandir($dir);
    echo '<ol class="song'.$myclass.'">';
    foreach($ffs as $ff){
    if($ff != '.' && $ff != '..'){
        echo '<li class="title'.$myclass.'">';
        if(is_dir($dir.'/'.$ff)){
            echo $ff;
            listFolderFiles($dir.'/'.$ff);
        }else{
            echo '<a href="'.$dir.'/'.$ff.'" target="_blank">'.$ff.'</a>';
        }
        echo '</li>';
    }
    }
    echo '</ol>';
    }
    listFolderFiles('Current Songs','_myclass');
    listFolderFiles('Current Songs','');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2016-02-05
      相关资源
      最近更新 更多