news_table:
id (PK)
title (varchar255)
time (INT 10) (UNIX timestamp)
content (text)
我希望按一个日期显示组
喜欢这种格式:
2014-12-16 << NEWS >>
title 2....
title 1....
2014-12-15 << NEWS >>
title 1....
2014-12-09 << NEWS >>
title 3....
title 2....
title 1....
我正在使用smarty
。
我是否需要在smarty
html
或php
或mysql
中执行某些操作?
答案 0 :(得分:1)
其实你需要这样的东西。首先将所有新闻放入一个数组中,并提供您提到的日期的关键字。然后遍历这个数组。代码未经过测试。
$sql = "SELECT * FROM news ORDER BY time DESC";
$res = mysqli_query($link, $sql);
$newsArray = array();
while ($row = mysqli_fetch_assoc($res)) {
$date = date("Y-m-d", $row["time"]);
if (!array_key_exists($date, $newsArray)) {
$newsArray[$date] = array();
}
$newsArray[$date][] = array(
'title' => $row['title'],
'content' => $row['contntent']
);
}
$oldDate = '';
foreach ($newsArray as $key => $news) {
if ($oldDate !== $key) {
echo "<p><strong>" . $key . " << NEWS >></strong></p>" . "\n";
$oldDate = $key;
} else {
foreach ($news as $oneNews) {
echo $oneNews["title"] . "<br />" . "\n";
}
}
}
答案 1 :(得分:1)
你可以将它们分组到php中的diffirent数组中,并在smarty中创建一个嵌套循环来获取数据。
php代码可能如下所示:
<?php
$data=array();
/* a query which orders by date*/
while($fetch=/*your code to fetch*/){
$date("d-m-Y",$fetch["time"])
if(!array_key_exists($date, $data)){
$data[$date]=array();
}
$data[$date]=$fetch;
}
/* your code to send to smarty*/
?>
聪明的代码:
{foreach from=$myArray key=k item=v}
<h1>{$k}</h1>
{foreach from=$v item=d}
your item html
{/foreach}
{/foreach}