我有一个 PHP 代码可以发布我所做的文章,但是从最旧到最新,我需要它从最新到最旧,所以顺序是问题这是我用来将帖子放入数组的函数:function getPublishedPosts() { // use global $conn object in function global $conn; $sql = "SELECT * FROM posts WHERE published=true"; $result = mysqli_query($conn, $sql); // fetch all posts as an associative array called $posts $posts = mysqli_fetch_all($result, MYSQLI_ASSOC); return $posts;}这是代码的可视化部分:<?php foreach ($posts as $post): ?> <div class="post" style="margin-left: 0px;"> <img src="<?php echo BASE_URL . '/static/' . $post['image']; ?>" class="post_image" alt=""> <a href="single_post.php?post-slug=<?php echo $post['slug']; ?>"> <div class="post_info"> <h3><?php echo $post['title'] ?></h3> <div class="post-body-div"> <?php echo html_entity_decode($post['body']); ?> </div> <div class="info"> <span><?php echo date("F j, Y ", strtotime($post["created_at"])); ?></span> </div> </div> </a> </div><?php endforeach ?>
2 回答
繁星coding
TA贡献1797条经验 获得超4个赞
只需使用 SQL 查询按 created_at 进行排序。像这样替换你的功能。
function getPublishedPosts() {
// use global $conn object in function
global $conn;
$sql = "SELECT * FROM posts WHERE published=true order by created_at desc";
$result = mysqli_query($conn, $sql);
// fetch all posts as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
return $posts;
}
料青山看我应如是
TA贡献1772条经验 获得超8个赞
您可以使用 array_reverse 反转保存帖子的数组
<?php foreach (array_reverse($posts) as $post): ?>
http://docs.php.net/manual/da/function.array-reverse.php
(当然最好使用 ORDER BY 对 SQL 进行排序,但我们需要有关可用数据库字段的更多信息。)
- 2 回答
- 0 关注
- 123 浏览
添加回答
举报
0/150
提交
取消