我正在使用一个简单的php新闻脚本,我想要选择查看单数帖子(而不是文件中的每个帖子,它是当前的工作方式)。
这是在前端使用的代码,我不确定我需要做什么,但我知道它涉及GET参数......
<?php
//get news class and array
include_once('newsadmin/includes/newsTools.class.inc.php');
$newsTools = new newsTools('newsadmin/csv/news.csv');
$news_headlines = $newsTools->getNewsArray();
//output news array as formatted html
if (!count($news_headlines)>0){
echo '<p>There are currently no news headlines.</p>';
}else{
foreach ($news_headlines as $key => $item){
list($news_id,$news_date,$news_title,$news_body) = $item;
$formatted_date = date('F j, Y, g:i a',$news_date);
echo <<<HTML
<a name="$news_id" id="$news_id"></a>
<h1 style="margin-bottom: 20px;">$news_title</h1>
$news_body
<p><span>Posted: $formatted_date</span></p>
<hr />
HTML;
}
}
?>
我认为它与此行有关: foreach($ news_headlines as $ key =&gt; $ item){
提前致谢:)
答案 0 :(得分:2)
我的建议是更改getNewsArray()
方法以不同方式构建您的$news_headlines
数组。
所以不要像这样的数组:
[
['NEWS ID VALUE', 'NEWS DATE VALUE', 'NEWS TITLE VALUE', 'NEWS BODY VALUE'],
['NEWS ID VALUE 2', 'NEWS DATE VALUE 2', 'NEWS TITLE VALUE 2', 'NEWS BODY VALUE 2'],
...
]
你可以像这样构建一个数组:
[
'NEWS ID VALUE' => ['NEWS DATE VALUE', 'NEWS TITLE VALUE', 'NEWS BODY VALUE'],
'NEWS ID VALUE 2' => ['NEWS DATE VALUE 2', 'NEWS TITLE VALUE 2', 'NEWS BODY VALUE 2'],
...
]
这里新闻ID是关联数组中的键。这样做是允许您从数组中查找新闻项而无需迭代数组。所以可以这样做:
//get news class and array
include_once('newsadmin/includes/newsTools.class.inc.php');
$newsTools = new newsTools('newsadmin/csv/news.csv');
$news_headlines = $newsTools->getNewsArray();
if(!empty($_GET['news_id'])) {
// a single news item was requested
$news_id = $_GET['news_id'];
if (isset($news_headlines[$news_id])) {
// the news item was found in the array
$news_item = $news_headlines[$news_id];
// display your story
var_dump($news_id,$news_item);
} else {
// they requested an invalid news item, show some error here
}
} else {
//output news array as formatted html
if (!count($news_headlines)>0){
echo '<p>There are currently no news headlines.</p>';
} else {
foreach ($news_headlines as $news_id => $item){
list($news_date,$news_title,$news_body) = $item;
$formatted_date = date('F j, Y, g:i a',$news_date);
?>
<a name="<?php echo $news_id; ?>" id="<?php echo $news_id; ?>"></a>
<h1 style="margin-bottom: 20px;"><?php echo $news_title; ?></h1>
<?php echo $news_body; ?>
<p><span>Posted: <?php echo $formatted_date; ?></span></p>
<hr />
<?php
}
}
}
?>
如果CSV文件中包含大量项目,则可能还需要考虑将此数据移动到数据库中。这样可以防止在只需要一个项目的情况下将所有数据加载到内存中,并且还可以更方便地执行按日期排序,按日期范围显示记录等操作,如果您可能想要执行此类操作下线。