对从/ /语句返回的数据进行排序?
I am trying to echo out a user's friend's posts. Basically a system that is similar to the main page on facebook when you are logged in. Currently when it comes to echoing out person's friend's posts, in the database table for that user, it has an adress to a text file. In this cercumstance the content of mine is: 1,3
, and the numbers are user id's of my friends. Then in the page where I want to echo out my friend's posts is this:
<?php
//echo $user_data['friend_list'];
$file = $user_data['friend_list'];
if($file != null)
{
$myFile = $file;
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
//echo $theData;
$friend = explode(',', $theData);
//echo "This is friend array size ".count($friend)."</br>";
for($i=0; $i < count($friend); $i++)
{
if($i >= 0)
{
echo "I'm friend ".$i." and I have the User ID ".$friend[$i]."</br>";
$result = mysql_query("SELECT * FROM posts WHERE user_id = $friend[$i] ORDER BY timestamp");
while($row = mysql_fetch_array($result))
{
$user_id = $row['user_id'];
echo $row['content'] . " " . username_from_user_id($user_id) . " said on ".$row['timestamp'];
echo "<br />";
}
echo "<br/>";
}
}
}
?>
That currently returns/echos out this:
I'm friend 0 and I have the User ID 1
Hey, this is the first post. Well, I hope you like this network! harrison said on 2013-03-25 22:50:52
Hey, this is the second post ever on this website. I am testing out retrieving text from a database! harrison said on 2013-03-25 22:52:52
I really like the post system so far! harrison said on 2013-03-25 22:57:52
Okay, so far on user's profiles, it shows the six latest posts. harrison said on 2013-03-25 23:06:55
Hey Chinzo! harrison said on 2013-04-13 17:11:46
I'm friend 1 and I have the User ID 3
Hey! matt said on 2013-03-29 00:07:05
haha matt said on 2013-03-29 01:31:12
How could I echo out all of the posts in order by timestamp? I am currently sorting each user individually's posts, but not all the posts from both of the users 1 and 3
as a whole. How could I do this?
Instead of a for
loop that processes one friend at a time, get all the posts in one query:
$result = mysql_query("SELECT * FROM posts WHERE user_id IN ($theData) ORDER BY timestamp") or die ("Query error: ". mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['content'] . " " . username_from_user_id($row['user_id']) . " said on ".$row['timestamp']. "<br>";
}