Toine Lille
Toine Lille

Reputation: 55

PHP/MySQL - Threading needs slightly different order

I have a MySQL table with id, parent and comment which I managed to order almost-as-it-should from latest to oldest. If a comment has no parent, this is set to 0.

The comments table: Table Image

Hereby my current code:

<?php

$con = mysqli_connect('host','username','password','database');

if (mysqli_connect_errno($con)) {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$comments = array();
$results = mysqli_query($con,"SELECT * FROM comments ORDER BY id DESC");
while ($row = mysqli_fetch_assoc($results)) {
 $parent = $row['parent'];
 $comments[$parent ? $parent : 0][] = $row;                                        
}

function thread($parent,$comments) {
 foreach ($comments[$parent] as $post) {
  echo "<div>";
  echo $post['comment'];
  $id = $post['id'];
   if (isset($comments[$id])) {
    thread($id,$comments);
   }
  echo "</div>";
 }
}

thread(0,$comments);     

?>

The above results in the following order (turned into a list for readability, you can do this in the code by turning the div tags into li and echoing ul tags around the foreach loop):

Notice that replies are ordered in a descending manner as well, just like the comments. Other than that it's completely fine and working like a charm. But this is what it's supposed to be like:

Shortly said: comments should be in descending order, replies in ascending. That is where I got stuck completely. Thanks a lot for your help!!

Upvotes: 1

Views: 71

Answers (1)

helmbert
helmbert

Reputation: 38014

You can use the array_reverse function to reverse the order of the items in an array:

$results = mysqli_query($con,"SELECT * FROM comments ORDER BY id DESC");
while ($row = mysqli_fetch_assoc($results)) {
    // ...
}

// Important bit: Reverse all threads except the main thread (id=0):
foreach ($comments as $key => $value) {
    if ($key !== 0) {
        $comments[$key] = array_reverse($value);
    }
}

function thread($parent,$comments) {
    // And so on...

Upvotes: 2

Related Questions