我打算写一个函数来动态创建文章和新闻列表,但是不知道确切的方法是什么
我有/articles
和/news
文件夹包含像article1.php
, article2.php
等文件。
这些文件包含变量$date
(发布日期),$type
(新闻/文章),$h1, $h2
(标题,副标题),$short
(短段落显示在列表中)。
我想创建这些文件的列表显示在一个页面上。
HTML:<div>
$content <!--here goes list of all articles/news-->
</div>
这样是不是更好:
1 .
- 在
articlelist.php
中写入while循环:
-
newslist.php
也是同样的循环。
(使用这种方法,例如按日期排序文章可能很困难。)
或者:
2。
- 创建
articlearray.php
和newsarray.php
文件,以数组形式存储每篇文章和新闻文件中的数据,格式为key : value = $date : [$type, $h1, $h2, $short]
- 创建
parsearray
函数解析整个给定数组到HTML(包含来自所有文件的数据) - 呼叫
articlelist.php
和newslist.php
中的$content = parsearray(...)
- 显示美元内容。
或者有其他更好的解决方案吗?
我没有任何数据库,因为文章/新闻实在太少了。如果真的有必要,我将使用一个,但目前请假设它应该用纯PHP完成。(我问这个问题也是为了学习,而不仅仅是实用。)
首先:建议在不同的文件中管理您的内容和代码(为了更好的可理解性和可维护性),但不是强制性的。我会选择以下方法。把你的内容分成三个文件:
-
index.php
(包含"主要"功能) -
data.php
(含数据) -
functions.php
(包含可调用函数)
// functions.php
function execute($module) {
global $data;
$content .= '<div>';
foreach($data[$module] as $item) {
$content .= '<span>' . $item['date'] . '</span>';
$content .= '<h1>'. $item['h1'] . '</h1>';
// $content .= ...
}
$content .= "</div>";
return $content;
}
现在您可以通过index.php?m=articles
或index.php?m=news
调用您的页面来显示您的文章或新闻。
旁注:这种方法使以后切换到数据库更容易。
标题>