我是非常新的PHP我搜索谷歌找到一个正确的脚本循环文件夹中的所有子文件夹并获取该子文件夹中的所有文件路径
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
所以我有文件夹'posts',其中我有子文件夹'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循环的正确语法是什么?我现在真的得到了基础知识
答案 0 :(得分:1)
看看这是否有效:)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
答案 1 :(得分:0)
<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;
?>
答案 2 :(得分:-1)
看看这个:
<?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>";
}