从数组中删除重复项

25
我使用以下代码来循环遍历我的数据库中的一个表:
$items_thread = $connection -> fetch_all($sql);

如果我将数组打印出来:

print_r($items_thread);

我会得到这个:
Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [1] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )

)

但我想要从数组中去除重复项,所以我使用了array_unique函数。

print_r(array_unique($items_thread));

我得到了下面奇怪的结果,不太是我想要的:

以下是需要翻译的内容:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

)

理想情况下,我认为它应该返回这个:
Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [1] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )

)

我该怎么做才能搞定它?是我使用了错误的PHP语法/默认函数吗?

7
array_unique()会将所有的数组缩减为一个,因为它将内部数组比较为字符串,并且所有的数组都会被评估为Array。因此每个数组都被视为相同。此外,在手册中指出:"请注意,array_unique()不适用于多维数组。" - BoltClock
感谢您的建议 - SELECT DISTINCT RecipientID。尽管我可以从中获取唯一值,但它并没有返回我需要的结果...您可以查看我之前在这里发布的帖子 - http://stackoverflow.com/questions/5032645/mysql-php-send-emails-to-the-members-who-fall-into-last-3-active-threads 谢谢。 - Run
9个回答

69

您可以使用array_unique函数来去除数组中的重复项。您只需要在函数中添加SORT_REGULAR标志即可:

$items_thread = array_unique($items_thread, SORT_REGULAR);

然而,正如bren建议的那样,如果可能的话,你应该在SQL中处理这个问题。


我已经找了大约半天了! - Oguzhan

7

你最好在SQL查询中过滤掉重复项,可以添加一个约束条件来获取唯一的收件人ID。


3
筛选不重复的RecipientID - BoltClock
@BoltClock 谢谢... 你能解释一下为什么这种方式比 array_unique() 更好吗? - CJ Ramki
1
@CJ Ramki:通过仅选择所需的行而不是从数据库中获取所有内容并丢弃不需要的行,您可以节省更少的资源。 - BoltClock
如果我有像这样的数组,array_unique()会比较字符串ArrayArray并产生结果吗? - CJ Ramki

4

要去除重复的值,可以使用array_unique()函数。其功能是接受一个数组并返回另一个没有重复值的数组。

array_unique()的一般描述如下:

General Format = array array_unique(array $array [, int $sort_flags=sort_string] )
Parameters     = array: Input array ->sort_flags:
    The second optional parameter is used to compare items as follows
         1. SORT_REGULAR - Normal
         2. SORT_NUMERIC - Numerically
         3. SORT_STRING - As
         4. string  SORT_LOCALE_STRING - As string, based on the current locale.
Return Value   = Another array without duplicate values 

示例1:

<?php
$array=array('cricket'=>11,'football'=>11,'chess'=>2);
echo"<br/><b>Initially the values of \$array is:</b><br/>";
var_dump($array);
echo"<br/><b>After removing the duplicates:</b><br/>";
print_r(array_unique($array));
?>

输出:

Initially the values of $array is:
array(3) {
  ["cricket"] => int(11)
  ["football"] => int(11)
  ["chess"] => int(2)
}

After removing the duplicates:
Array
(
    [cricket] => 11
    [chess] => 2
)

1

试试这个:

$data = array_map('unserialize', array_unique(array_map('serialize', $data)));

输出以下内容:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => info@xx.com
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => lau@xx.co.uk
        )
)

但我认为你也应该在数据库中实现这个功能。此外,查看我的其他答案和解决方案。


谢谢您!那么 $items_thread = array_unique($items_thread, SORT_REGULAR); 呢?它返回与您的代码相同的结果吗? - Run
@lauthiamkok:我从来没有这样做过,它真的会返回相同的输出吗?如果是,太好了! - Alix Axel
@lauthiamkok:我已经阅读了手册,该标志似乎可以提供正确的结果,但请注意它仅适用于PHP >= 5.2.9。 - Alix Axel
谢谢。我正在使用PHP 5.3.x,我的线上环境也是5.3.x,所以我认为我很安全!非常感谢! - Run

1
您可以使用这段代码,希望它能对您有所帮助。它是完全可用的:
$array = array(1,1,2,3,4,4,4,5);
$temp=array();

for($i=0; $i<=count($array); $i++)
 {

    if($array[$i] != '')
    {
        for($j=$i+1; $j<=count($array); $j++ )
        {
            if($array[$i]==$array[$j])
            {
                $array[$j] = '';
            }
            else
            {
                $temp[$array[$i]]=$array[$i];
            }

         }

    }
}

print_r($temp); 

0
你可以使用普通的 PHP 数组来实现这个功能。
$newArray = array();
foreach ($origArray as $user)
{
   $newArray[$user['RecipientID']] = $user;
}

0
请查看下面的代码,希望对您有所帮助。
$resultArray = uniqueAssocArray($actualArray, 'RecipientID');

function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
    return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
    $groupBy=$item[$uniqueKey];
    if (isset( $uniqueKeys[$groupBy]))
    {
        //compare $item with $uniqueKeys[$groupBy] and decide if you 
        //want to use the new item
        $replace= false; 
    }
    else
    {
        $replace=true;
    }
    if ($replace) $uniqueKeys[$groupBy] = $item;   
}
return $uniqueKeys;

}


0

0
$res1       = mysql_query("SELECT * FROM `luggage` where r_bus_no='".$tour_id."' and `date1`='$date' AND `login_id`='".$_SESSION['login_id']."'");
}
/// create a array to store value
$city_arr   = array();
if(mysql_num_rows($res1)>0)
{
    while($row1 = mysql_fetch_array($res1))
    {

/// insert the value in array use the array_push function
            array_push($city_arr,$row1['r_to']);
    }

//// remove the duplicate entry in array use the array_unique function
    $a          = array_unique($city_arr);
    echo "<option value='' selected='selected'> -- Select City ---</option>";
    foreach($a as $b)
    {
    ?>
    <option value="<?php echo $b ;?>"><?php echo city($b); ?></option>
    <?php       
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接