1

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 :)

My code:

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>
Marc Delisle
  • 8,879
  • 3
  • 29
  • 29

1 Answers1

2

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

Example:

<?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";
}
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129