我不确定这是MySQL问题还是PHP问题。如果可以在SQL中解决它的首选。
目前我有以下内容:
$sql=$dbh->prepare("SELECT DISTINCT ToUserID, FromUserID FROM Message WHERE Deleted is NULL AND (ToUserID=? OR FromUserID=?)");
$sql->execute(array($_POST['UserID'], $_POST['UserID']));
$messages = $sql->fetchAll();
MySQL查询可能返回如下内容:
{
"ToUserID" : "1",
"1" : "2",
"0" : "1",
"FromUserID" : "2"
},
{
"ToUserID" : "2",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
}
我需要的是能够过滤结果,以便上面两个结果只返回一个。即
if (item1.ToUserID == item2.FromUserID) && (item1. FromUserID == item2.toUserID) {
remove item2
}
另一个例子:
{
"ToUserID" : "1",
"1" : "2",
"0" : "1",
"FromUserID" : "2"
},
{
"ToUserID" : "2",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
},
{
"ToUserID" : "3",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
},
{
"ToUserID" : "4",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
},
{
"ToUserID" : "4",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
}
会变成:
{
"ToUserID" : "1",
"1" : "2",
"0" : "1",
"FromUserID" : "2"
},
{
"ToUserID" : "3",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
},
{
"ToUserID" : "4",
"1" : "1",
"0" : "2",
"FromUserID" : "1"
}
答案 0 :(得分:1)
无关紧要,我会将默认提取模式更改为PDO_FETCH_ASSOC,这样您就不需要为编号键而烦恼,而这些键只是重复信息。
然后,这些组合
1 2 User1
2 3 User2
2 1 User2
你想要消除User2的第二次出现,因为1-2对已经存在。
您可以通过添加两个计算字段在MySQL中执行此操作:
SELECT ...
... IF (user1 < user2, user1, user2) AS oneUser,
... IF (user1 < user2, user2, user1) AS anotherUser,
...
现在,两行都将两个额外的字段设置为&#34; 1&#34;和&#34; 2&#34;,你可以为这些添加一个明确的约束。
当然你也可以在PHP中这样做:
// Array
$seen = [ ];
while ($tuple = $rs->fetch()) {
$key = $tuple['user1id'] < $tuple['user2id']
? "{$tuple['user1id']}:{$tuple['user2id']}"
: "{$tuple['user2id']}:{$tuple['user1id']}";
if (in_array($key, $seen)) {
// Ignore this tuple.
continue;
}
// Add combination to seen list
$seen[] = $key;
...
}