You can do this in one request, which is fine if the amount of data in your original posts is small :
$getPost = mysql_query('SELECT p.*, r.reply_id, r.username r_username, r.reply_content, r.timestamp r_timestamp FROM post p left join reply r ORDER BY p.post_id DESC' ); $posts = array(); $last_id = 0; while($row = mysql_fetch_array($getPost)) { if ($last_id != $row['post_id']) { $posts[] = array( 'post_id' => $row['post_id'], 'user_id' => $row['user_id'], 'username' => $row['username'], 'content' => $row['content'], 'timestamp' => $row['timestamp'], 'comments' => array() ); } $posts[sizeof($posts) - 1]['comments'][] = array( 'reply_id' => $row['reply_id'], 'username' => $row['r_username'], 'reply_content' => $row['reply_content'], 'timestamp' = $row['r_timestamp'] ); }
Otherwise, divide it into two queries:
$getPost = mysql_query('SELECT p.*, FROM post p ORDER BY p.post_id DESC' ); $rows = array(); $ids = array(); $index = array(); while($row = mysql_fetch_assoc($getPost)) { $row['comments'] = array(); $rows[] = $row; $ids[] = $row['post_id']; $index[$row['post_id']] = sizeof($rows) - 1; } $getComments = mysql_query('select r.* from replies r where r.post_id in ("' . join('","', $ids) . '")'); while ($row = mysq_fetch_assoc($getComments)) { $rows[$index[$row['post_id']]]['comments'][] = $row; }
... Or something like that. Any option allows you to clog your first request with WHERE clauses, etc. For your heartfelt content. The advantage of the second approach is that you do not retransmit your original data for each comment!
source share