防止数组

时间:2017-11-30 18:17:58

标签: php arrays

要理解这个问题,请先查看此代码:

$thuser = $_SESSION['username']; //current user
$sql = "SELECT sender FROM dm WHERE receiver = '$thuser'";

if ($result = mysqli_query($link, $sql)) {
    $t = 1;

    while ($partner = $result->fetch_row()) {
        $ptr = 'Partner'.$t;
        $chatpartners[$ptr] = $partner[0];
        $t++;
    };
} 
echo json_encode($chatpartners);

现在,sql查询将选择多个发件人,例如" John"," Eric"," James"," James"。

我的问题是,我怎样才能阻止詹姆斯"从被插入数组两次。

数组看起来像这样:

{ Partner1: "John", Partner2: "Eric", Partner3: "James" }

这样:

{ Partner1: "John", Partner2: "Eric", Partner3: "James", Partner4: "James" }

如何实现?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在你的SQL查询中使用DISTINCT,如下所示:

$sql = "SELECT DISTINCT sender FROM dm WHERE receiver = '$thuser'";

另一种选择是像这样使用array_unique

$chatpartners = ['Partner1' => "John", 'Partner2' => "Eric", 'Partner3' => "James", 'Partner4' => "James"];

$chatpartners = array_unique($chatpartners);

echo json_encode($chatpartners);

输出:

{"Partner1":"John","Partner2":"Eric","Partner3":"James"}