php 从数组中删除重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5036403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:36:03  来源:igfitidea点击:

Remove duplicate items from an array

phparraysduplicatesarray-unique

提问by laukok

I use the line of code below to loop through a table in my database:

我使用下面的代码行遍历数据库中的表:

$items_thread = $connection -> fetch_all($sql);

And if I print the array out:

如果我打印出数组:

print_r($items_thread);

I will get this:

我会得到这个:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [1] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )

)

But I want to get rid of the duplicate items in the array, so I use array_unique

但我想摆脱数组中的重复项,所以我使用 array_unique

print_r(array_unique($items_thread));

I get the weird result below which is not quite I am looking for:

我得到以下奇怪的结果,这并不是我想要的:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

)

Ideally, I think it should return this:

理想情况下,我认为它应该返回:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [1] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )

)

What shall I do to get it right? Have I used the wrong PHP syntax/default function?

我该怎么做才能做到正确?我是否使用了错误的 PHP 语法/默认函数?

回答by Tim Cooper

The array_uniquefunction will do this for you. You just needed to add the SORT_REGULARflag:

array_unique函数将为您执行此操作。您只需要添加SORT_REGULAR标志:

$items_thread = array_unique($items_thread, SORT_REGULAR);

However, as brensuggests, you should do this in SQL if possible.

但是,正如bren 所建议的,如果可能,您应该在 SQL 中执行此操作。

回答by bren

You'd be much better off filtering out the duplicates in the SQL query. add a constraint which fetches a UNIQUE recipientID

您最好过滤掉 SQL 查询中的重复项。添加获取唯一收件人 ID 的约束

回答by bren

To remove duplicate values then we can use array_unique()function. The functionality of it is to accept an array and returns another array without duplicate values.

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

General description of array_unique() is given below:

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 

Example 1:

示例 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));
?>

Output:

输出:

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
)

回答by Alix Axel

Try this:

尝试这个:

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

Outputs the following:

输出以下内容:

Array
(
    [0] => Array
        (
            [RecipientID] => 3
            [RecipientScreenname] => Tom L
            [RecipientFirstname] => Thomas
            [RecipientEmail] => [email protected]
        )

    [2] => Array
        (
            [RecipientID] => 1
            [RecipientScreenname] => Lau T
            [RecipientFirstname] => TK
            [RecipientEmail] => [email protected]
        )
)

But I also think you should implement this in your database. Also, check my other answerand solutions.

但我也认为你应该在你的数据库中实现它。另外,请检查我的其他答案和解决方案。

回答by Rajat Singh

You can use this code and I hope it will help you. It's completely working:

您可以使用此代码,希望对您有所帮助。它完全有效:

$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); 

回答by H A?d?μ

$unique = array_keys(array_flip($array));

$unique = array_keys(array_flip($array));

It's is faster, plus it reset the array key index.

它更快,而且它重置了数组键索引。

source: http://php.net/manual/en/function.array-unique.php#89519

来源http: //php.net/manual/en/function.array-unique.php#89519

This only for a simple array.

这仅适用于简单数组。

回答by Raju Dudhrejiya

Please check below code, I hope this is help full for you.

请检查下面的代码,我希望这对您有帮助。

$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;

}

}

回答by suresh kumawat

$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       
    }
}

回答by Byron Whitlock

You can use the regular php arrays to achieve this.

您可以使用常规的 php 数组来实现这一点。

$newArray = array();
foreach ($origArray as $user)
{
   $newArray[$user['RecipientID']] = $user;
}