如何删除PHP中的数据重复?

时间:2012-12-10 14:23:11

标签: php mysql

我有一个php问题,我想把结果如下:

123 *托马斯*蒂芙尼*凯瑟琳*恩恩*加布里埃尔*伊丽莎白*阿哇*

但结果如下:

123 * 123 * 123 * 123 * 123 *托马斯*托马斯*托马斯*托马斯*蒂芙尼*蒂芙尼*蒂芙尼*蒂芙尼*凯瑟琳*凯瑟琳*凯瑟琳*凯瑟琳*凯瑟琳*恩恩*恩恩*恩恩*恩恩*加布里埃尔*加布里埃尔* Gabriel * Gabriel * Elizabeth * Elizabeth * Elizabeth * Elizabeth * Ah Goh * Ah Goh * Ah Goh * Ah Goh * Ah Goh *

任何人都可以告诉我如何解决这个问题?感谢。

以下是代码:

$name = $_POST['Username'];

$data = mysql_query("SELECT * FROM User");                 
$data1 = mysql_query("SELECT Friends.responseRequest FROM User INNER JOIN Friends ON 
            User.username = Friends.sentRequest WHERE User.username = '$name' AND     Friends.status = 'approved'")or die(mysql_error());; 

$data2=mysql_query("SELECT Friends.sentRequest FROM User INNER JOIN Friends ON User.username = Friends.responseRequest WHERE User.username = '$name'
                 AND Friends.status = 'approved'");   


    $user = array();
    while($info1 = mysql_fetch_array($data)){
    array_push($user, $info1[username]);
    }

$friend =array();
     $getFriend1 = mysql_query("SELECT * FROM Friends WHERE sentRequest='$name' AND status='approved'");
     $getFriend2 = mysql_query("SELECT * FROM Friends WHERE responseRequest='$name' AND status='approved'"); 

     while($info2 = mysql_fetch_array($getFriend1)){
    array_push($friend , $info2[responseRequest]);
    }

     while($info3 = mysql_fetch_array($getFriend2)){
    array_push($friend , $info3[sentRequest]);
    }

    $newFriend = array_unique($friend);
    $newUser=array();
    for($i=0;$i<count($user);$i++){
        for($j=0;$j<count($newFriend);$j++){
            if($newFriend[$j]!=$user[$i]&&$user[$i]!=$name){
                echo $user[$i]."*";
            }
        }

    }

    mysql_close();

1 个答案:

答案 0 :(得分:4)

一种简单的方法(不一定是最好的方法)是将结果拆分为数组,消除重复项,然后再次连接部分。

<?php
$str = '123*123*123*123*123*thomas*thomas*thomas*thomas*Tiffany*Tiffany*Tiffany*Tiffany*Catherine*Catherine*Catherine*Catherine*Catherine*EnEn*EnEn*EnEn*EnEn*Gabriel*Gabriel*Gabriel*Gabriel*Elizabeth*Elizabeth*Elizabeth*Elizabeth*Ah Goh*Ah Goh*Ah Goh*Ah Goh*Ah Goh*';
$aux = array_unique(explode('*', $str));
$str = implode('*', $aux);