使帖子在博客页面上显示为最新到最旧

我有一个 PHP 代码可以发布我所做的文章,但是从最旧到最新,我需要它从最新到最旧,所以顺序是问题

http://img4.mukewang.com/618f9a2e00018db711430290.jpg

这是我用来将帖子放入数组的函数:


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 ?>


慕桂英4014372
浏览 126回答 2
2回答

繁星coding

只需使用 SQL 查询按 created_at 进行排序。像这样替换你的功能。function getPublishedPosts() {&nbsp; &nbsp; // use global $conn object in function&nbsp; &nbsp; global $conn;&nbsp; &nbsp; $sql = "SELECT * FROM posts WHERE published=true order by created_at desc";&nbsp; &nbsp; $result = mysqli_query($conn, $sql);&nbsp; &nbsp; // fetch all posts as an associative array called $posts&nbsp; &nbsp; $posts = mysqli_fetch_all($result, MYSQLI_ASSOC);&nbsp; &nbsp; return $posts;}

料青山看我应如是

您可以使用 array_reverse 反转保存帖子的数组<?php&nbsp;foreach&nbsp;(array_reverse($posts)&nbsp;as&nbsp;$post):&nbsp;?>http://docs.php.net/manual/da/function.array-reverse.php(当然最好使用 ORDER BY 对 SQL 进行排序,但我们需要有关可用数据库字段的更多信息。)
打开App,查看更多内容
随时随地看视频慕课网APP