简体   繁体   中英

Give unique class to list item in php array

I have created an array that displays the all the files within several sub-directories of one single directory (A directory tree essentially). The files are all links that open the file within that directory when clicked.

The issue I am having is that I want to be able to style my results, however all sub-directories and file names have the same class (as they are generated using the same code).

Here is my 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');

?>

And the html generated is this:

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

As you can see, each entry is made up of 2 ordered lists, however they both have the same class, as do all the list items, which makes it near impossible to do any styling to.

What I want is the following html markup to be generated:

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

Can anyone please give some advice on what php changes I need to make to my code in order to output the above.

you can pass the class name also as a prameter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM