虽然循环按顺序基于关联数组php?

时间:2011-11-18 08:08:51

标签: php mysql loops while-loop

我有以下代码用于显示简单朋友系统发送,接收和接受的邀请。

while ($friend = $q -> fetch(PDO::FETCH_ASSOC)) {
      if ($friend['id'] == $user['id'] && $friend['friendAccept'] == 0) echo '<p>You have sent a request to be <a href="http://www.n.com/viewaccount?id=' . $friend['withID'] . '">' . $friend['username'] . '\'s</a> friend.</p>';
      if ($friend['withID'] == $user['id'] && $friend['friendAccept'] == 0) echo '<p>You have recieved a request from <a href="http://www.n.com/viewaccount?id=' . $friend['withID'] . '">' . $friend['username'] . '</a>.</p>';
      if ($friend['id'] == $user['id'] && $friend['friendAccept'] == 1) echo '<p>You are friends with <a href="http://www.n.com/viewaccount?id=' . $friend['withID'] . '">' . $friend['username'] . '</a>.</p>';
}

它会显示您的朋友,您发送的朋友请求以及收到的朋友请求。我从一个mysql查询中得到了所有这些。但唯一的问题是它们不是有序的,因为while循环在列表中迭代并做它应该做的任何事情。

有没有办法在仍然只使用一个查询的同时使它们按顺序排列?按顺序我指的是在一个列表中收到的所有请求,在一个列表中发送的请求以及在一个列表中的朋友。因为它们是在他们从桌子上被拉出的顺序。

查询...

$q = $dbc -> prepare("SELECT social.*, accounts.username FROM social INNER JOIN accounts WHERE social.withID = accounts.ID AND (social.id = ? OR social.withID = ?) AND type = 'friend'");
$q -> execute(array($user['id'], $user['id']));

3 个答案:

答案 0 :(得分:1)

绝对可能:

SELECT social.*, accounts.username 
FROM social 
INNER JOIN accounts 
WHERE social.withID = accounts.ID 
AND (social.id = ? OR social.withID = ?) 
AND type = 'friend'
ORDER BY 
(social.id = $user_id AND social.friendAccept = 0), 
(social.withID = $user_id AND social.friendAccept = 0),
(social.id = $user_id AND social.friendAccept = 1)

只需按正确顺序放置ORDER BY子句即可。这种方式有效,它使用表达式计算的布尔值对它进行排序。

当然,你还应该将$ user_id转换为?在准备好的声明中。

答案 1 :(得分:0)

您可以更改SQL查询以执行

ORDER BY x ASC/DESC

或者您可以在PHP中创建一个结果数组,然后使用任何PHP排序函数根据任何条件对数组进行排序。

有关详细信息,请参阅http://php.net/manual/en/array.sorting.php

编辑:我想

uasort()

可能会有所帮助。您可以定义自己的比较函数,然后PHP将根据它进行排序。有关详情,请参阅http://www.php.net/manual/en/function.uasort.php

答案 2 :(得分:0)

$q = $dbc -> prepare("SELECT social.*, accounts.username FROM social INNER JOIN accounts WHERE social.withID = accounts.ID AND (social.id = ? OR social.withID = ?) AND type = 'friend' ORDER BY social.friendAccept ASC");
$q -> execute(array($user['id'], $user['id']));

ORDER BY social.friendAccept

首先不会被用户接受。

如果您提供一些数据示例,我可以提供更多帮助