我需要进入一个名为“ People”的目录,并提取文件夹名称,然后构造一些HTML,这些HTML使用目录的内容构建链接。
我选择一个名为“ article-number-one”的文件夹,并根据该文件夹的名称显示标题,链接,缩略图和摘录。
这是我的代码。除订购外,它均有效。这是字母顺序的。我希望按创建日期...最重要的是最新的
<?php
$files = glob("people/*");
foreach($files as $file)
{
echo '<div class="block"><a href="people/'.basename($file).'"><img src="people/'.basename($file).'/'.basename($file).'-thumbnail.jpg" height="180" width="320" alt="'.basename($file).'"/></a><br/><br/>';
echo '<a href="people/'.basename($file).'">'.str_replace('-', ' ', basename($file, "")).'</a><br/><div class="excerpt">';
include 'people/'.basename($file).'/'.basename($file).'-excerpt.txt';
echo '</div><hr></div>';
}
?>
请帮助我订购最新到最旧的HTML。
答案 0 :(得分:0)
usort($files, function($a, $b) {
return ($a['date'] < $b['date']) ? -1 : 1;
});
答案 1 :(得分:0)
分几个步骤进行。这样,您就可以检查出它如何进行并分别测试每个步骤。
// Get an array with all useful file info
$fileInfo = array_map(
function($filename) {
$short = basename($filename);
// Excerpt
$excerpt = $filename . DIRECTORY_SEPARATOR . $short . '-excerpt.txt';
if (is_readable($excerpt)) {
$text = trim(file_get_contents($excerpt));
} else {
$text = 'Excerpt not available';
}
return [
'full' => $filename,
'base' => $short,
'thumb' => $filename . DIRECTORY_SEPARATOR . $short . '.jpg',
'name' => ucwords(str_replace('-', ' ', $short)),
'date' => filectime($filename),
'text' => $text,
];
},
glob("people/*", GLOB_ONLYDIR)
);
对数组排序:
// Now sort the array. Have a function decide when a file is before another
usort($fileInfo, function($info1, $info2) {
if ($info1['date'] < $info2['date']) {
return 1;
}
if ($info1['date'] > $info2['date']) {
return -1;
}
return 0;
});
最后,您将HTML包含在一个变量中。通常,尽可能减少回显/打印是一件好事。混合PHP和输出可能是维护的噩梦。
// Get the HTML. You could put this in a .html file of its own
// such as 'template.html' and read it with
// $template = trim(file_get_contents('template.html'));
$template = <<<INFO2HTML
<div class="block">
<a href="{base}"><img
src="{thumb}"
height="180" width="320"
alt="{base}"/></a>
<br />
<br />
<a href="{base}">{name}</a>
<br />
<div class="excerpt">{text}</div>
<hr />
</div>
INFO2HTML;
// Repeat the parsing of the template using each entry
// to populate the variables.
$html = implode('', array_map(
function($info) use($template) {
return preg_replace_callback(
'#{(.*?)}#',
function($keys) use ($info) {
return $info[$keys[1]];
},
$template
);
},
$fileInfo
));
print $html;
$ mkdir people
$ mkdir people/joe-smith
$ echo "this is the excerpt" > people/joe-smith/joe-smith-excerpt.txt
$ touch people/joe-smith/joe-smith-thumbnail.jpg
$ ls -R people
people:
joe-smith
people/joe-smith:
joe-smith-excerpt.txt
joe-smith-thumbnail.jpg
样品运行输出:
<div class="block"> <a href="joe-smith"><img src="people/joe-smith/joe-smith.jpg" height="180" width="320" alt="joe-smith"/></a> <br /> <br /> <a href="joe-smith">Joe Smith</a> <br /> <div class="excerpt">this is the excerpt</div> <hr /> </div>