在ID之后对Foreach循环进行排序 [英] Sort Foreach Loop after ID

查看:73
本文介绍了在ID之后对Foreach循环进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在ID之后对foreach循环的结果进行排序?以最高的ID开头,以此类推...既然是文章,我希望以最高的ID(最新的)开头:)

Is it possible to sort the result of a foreach loop after the ID? With the highest ID first and so on... Since it's articles I want the highest ID (newest) to be first :)

我的代码:

include_once('includes/connection.php');
include_once('includes/article.php');

$article = new Article;
$articles = $article->fetch_all();



?>
<html>
    <head>
        <title>CMS</title>
        <link rel="stylesheet" href="assets/style.css" />
    </head>

    <body>
        <div class="container">
            <a href="index.php" id="logo">CMS</a>

            <ol>
                <?php foreach ($articles as $article) { ?>
                    <li>
                        <a href="article.php?id=<?php echo $article['article_id']; ?>">
                            <?php echo $article['article_title']; ?>
                        </a>

                        - <small>
                            Posted <?php echo date('l jS', $article['article_timestamp']); ?>
                        </small>
                    </li>
                <?php } ?>
            </ol>

            <br />

            <small><a href="admin">Admin Login</a></small>

        </div>
    </body>
</html>

推荐答案

您正在寻找根据article_id字段对数组$articles进行排序的方法-可以使用功能

You're looking for sorting the array $articles according to article_id field - which can be done using the function usort.

示例:

<?php
function cmp($a, $b)
{
    if ($a['article_id'] == $b['article_id']) {
        return 0;
    }
    return ($a['article_id'] < $b['article_id']) ? -1 : 1;
}


usort($articles, "cmp");

foreach ($articles as $article) {
    echo "$article: ". $article['article_id']." \n";
}

这篇关于在ID之后对Foreach循环进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆