我真的很陌生 PHP 我搜索了谷歌以找到一个正确的脚本,该脚本循环访问文件夹中的所有子文件夹并获取该子文件夹中的所有文件路径
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
所以我有文件夹"帖子",其中我有两个文件的子文件夹"post001"
controls.png
text.txt
上面的代码呼应了这一点
posts'.
posts'..
posts'post001'.
posts'post001'..
posts'post001'controls.png
posts'post001'text.txt
但是我只想像这样回显这些子文件夹中的文件路径
posts'post001'controls.png
posts'post001'text.txt
这样做的重点是我想为每个子文件夹动态创建div,在这个div 中,我将 img 与 src 和一些 h3 和 p html 标签放在文本等于.txt文件,所以这是这样做的正确方法以及如何重新制作我的 php 脚本,以便我只获得文件路径
所以我可以看到答案,它们都是正确的,但现在我的观点是我需要这样的东西
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
那么在 php 中执行这两个 foreach 循环的正确语法是什么,我现在真的掌握了基础知识
看看这是否有效:)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
看看这个:
<?php
$filename[] = 'posts'.';
$filename[] = 'posts'..';
$filename[] = 'posts'post001'.';
$filename[] = 'posts'post001'..';
$filename[] = 'posts'post001'controls.png';
$filename[] = 'posts'post001'text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
结果:
posts'post001'controls.png
posts'post001'text.txt
这样做的目的是检查倒数第 4 位数字是否为点。如果是这样,它是三个字母的扩展名,它应该是一个文件。您还可以检查特定的扩展名。
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}