我正在使用DirectoryIterator生成PDF文件的链接列表.(还有一些代码来分解文件名以使列表更加用户友好.)我想按文件名对结果进行排序,但无法弄清楚如何.我知道我需要将结果放入数组中,然后对数组进行排序.但是,我无法在任何地方找到一个像我一样的例子,所以我无法弄清楚如何将数组/排序集成到我的代码中,因为我的PHP很弱.有人可以借助吗?
($ path在页面的其他地方声明)
<?php
if (is_dir($path))
{
print '<ul>';
foreach (new DirectoryIterator($path) as $file)
{
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$pieces = explode('.', $fileName);
$date = explode('-', $pieces[2]);
$filetypes = array(
"pdf",
"PDF"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes))
{
print '<li><a href="' . $path . '' . $fileName . '">' . $pieces[2] . '</a></li>';
}
}
print '</ul>';
}
else
{
print $namePreferred . ' are not ready.</p>';
}
?>
Run Code Online (Sandbox Code Playgroud)
Mac*_*eeE 10
将您的有效文件放入一个包含各种列的数组中,您可以将其排序,这可能是最好的选择,也可以是相关联的.
我使用asort() " 排序数组并保持索引关联 ",我认为最符合您的要求.
if (is_dir($path)) {
$FoundFiles = array();
foreach (new DirectoryIterator($path) as $file) {
if ($file->isDot())
continue;
$fileName = $file->getFilename();
$pieces = explode('.', $fileName);
$date = explode('-', $pieces[2]);
$filetypes = array(
"pdf",
"PDF"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if ( in_array( strtolower( $filetype ), $filetypes )) {
/**
* Place into an Array
**/
$FoundFiles[] = array(
"fileName" => $fileName,
"date" => $date
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
print_r( $FoundFiles );
Array
(
[0] => Array
(
[fileName] => readme.pdf
[date] => 22/01/23
)
[1] => Array
(
[fileName] => zibra.pdf
[date] => 22/01/53
)
[2] => Array
(
[fileName] => animate.pdf
[date] => 22/01/53
)
)
Run Code Online (Sandbox Code Playgroud)
asort()
/**
* Sort the Array by FileName (The first key)
* We'll be using asort()
**/
asort( $FoundFiles );
/**
* After Sorting
**/
print_r( $FoundFiles );
Array
(
[2] => Array
(
[fileName] => animate.pdf
[date] => 22/01/53
)
[0] => Array
(
[fileName] => readme.pdf
[date] => 22/01/23
)
[1] => Array
(
[fileName] => zibra.pdf
[date] => 22/01/53
)
)
Run Code Online (Sandbox Code Playgroud)
}
然后在函数完成后使用HTML进行打印 - 您的代码在代码处于循环中时执行了此操作,这意味着您无法在已经打印之后对其进行排序:
<ul>
<?php foreach( $FoundFiles as $File ): ?>
<li>File: <?php echo $File["fileName"] ?> - Date Uploaded: <?php echo $File["date"]; ?></li>
<?php endforeach; ?>
</ul>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14415 次 |
最近记录: |