php 如何从PHP中的多维数组中删除重复值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/307674/
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-24 22:19:52  来源:igfitidea点击:

How to remove duplicate values from a multi-dimensional array in PHP

phparraysduplicate-data

提问by Ian

How can I remove duplicate values from a multi-dimensional array in PHP?

如何从 PHP 中的多维数组中删除重复值?

Example array:

示例数组:

Array
(
    [0] => Array
    (
        [0] => abc
        [1] => def
    )

    [1] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [2] => Array
    (
        [0] => mno
        [1] => pql
    )

    [3] => Array
    (
        [0] => abc
        [1] => def
    )

    [4] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [5] => Array
    (
        [0] => mno
        [1] => pql
    )

)

回答by daveilers

Here is another way. No intermediate variables are saved.

这是另一种方式。不保存中间变量。

We used this to de-duplicate results from a variety of overlapping queries.

我们使用它从各种重叠查询中删除重复结果。

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

回答by Ja?ck

Since 5.2.9 you can use array_unique()if you use the SORT_REGULARflag like so:

从 5.2.9 开始,array_unique()如果您SORT_REGULAR像这样使用标志,则可以使用:

array_unique($array, SORT_REGULAR);

This makes the function compare elements for equality as if $a == $bwere being used, which is perfect for your case.

这使得函数比较元素的相等性就好像$a == $b正在使用一样,这非常适合您的情况。

Output

输出

Array
(
    [0] => Array
        (
            [0] => abc
            [1] => def
        )

    [1] => Array
        (
            [0] => ghi
            [1] => jkl
        )

    [2] => Array
        (
            [0] => mno
            [1] => pql
        )

)

Keep in mind, though, that the documentationstates:

但请记住,文档指出:

array_unique()is not intended to work on multi dimensional arrays.

array_unique()不适用于多维数组。

回答by Rajendrasinh

I had a similar problem but I found a 100% working solution for it.

我有一个类似的问题,但我找到了一个 100% 有效的解决方案。

<?php
    function super_unique($array,$key)
    {
       $temp_array = [];
       foreach ($array as &$v) {
           if (!isset($temp_array[$v[$key]]))
           $temp_array[$v[$key]] =& $v;
       }
       $array = array_values($temp_array);
       return $array;

    }


$arr="";
$arr[0]['id']=0;
$arr[0]['titel']="ABC";
$arr[1]['id']=1;
$arr[1]['titel']="DEF";
$arr[2]['id']=2;
$arr[2]['titel']="ABC";
$arr[3]['id']=3;
$arr[3]['titel']="XYZ";

echo "<pre>";
print_r($arr);
echo "unique*********************<br/>";
print_r(super_unique($arr,'titel'));

?>

回答by OIS

Another way. Will preserve keys as well.

其它的办法。也将保留密钥。

function array_unique_multidimensional($input)
{
    $serialized = array_map('serialize', $input);
    $unique = array_unique($serialized);
    return array_intersect_key($input, $unique);
}

回答by Jeremy Ruten

The user comments on the array_unique()documentation have many solutions to this. Here is one of them:

用户对array_unique()文档的评论对此有很多解决方案。这是其中之一:

kenrbnsn at rbnsn dot com
27-Sep-2005 12:09

Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.

This function uses the serialize, array_unique, and unserialize functions to do the work.


function multi_unique($array) {
    foreach ($array as $k=>$na)
        $new[$k] = serialize($na);
    $uniq = array_unique($new);
    foreach($uniq as $k=>$ser)
        $new1[$k] = unserialize($ser);
    return ($new1);
}

kenrbnsn 在 rbnsn dot com
27-Sep-2005 12:09

另一个 Array_Unique 用于多维数组。我只在二维数组上测试过这个,但它可能会被推广到更多,或者使用递归。

该函数使用 serialize、array_unique 和 unserialize 函数来完成这项工作。


function multi_unique($array) {
    foreach ($array as $k=>$na)
        $new[$k] = serialize($na);
    $uniq = array_unique($new);
    foreach($uniq as $k=>$ser)
        $new1[$k] = unserialize($ser);
    return ($new1);
}

This is from http://ca3.php.net/manual/en/function.array-unique.php#57202.

这是来自http://ca3.php.net/manual/en/function.array-unique.php#57202

回答by automatix

If "remove duplicates" means "remove duplicates, but let one there", a solution might be to apply the array_unique(...)on the "identifier column" first and then to remove in the original array all the keys, that have been removed from the column array:

如果“删除重复项”的意思是“删除重复项,但保留一个”,则解决方案可能是先array_unique(...)在“标识符列”上应用 ,然后在原始数组中删除所有已从列数组中删除的键:

$array = [
    [
        'id' => '123',
        'foo' => 'aaa',
        'bar' => 'bbb'
    ],
    [
        'id' => '123',
        'foo' => 'ccc',
        'bar' => 'ddd'
    ],
    [
        'id' => '567',
        'foo' => 'eee',
        'bar' => 'fff'
    ]
];

$ids = array_column($array, 'id');
$ids = array_unique($ids);
$array = array_filter($array, function ($key, $value) use ($ids) {
    return in_array($value, array_keys($ids));
}, ARRAY_FILTER_USE_BOTH);

The result is:

结果是:

Array
(
    [0] => Array
        (
            [id] => 123
            [foo] => aaa
            [bar] => bbb
        )

    [2] => Array
        (
            [id] => 567
            [foo] => eee
            [bar] => fff
        )

)

回答by Mahak Choudhary

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => john
        )

    [1] => Array
        (
            [id] => 2
            [name] => smith
        )

    [2] => Array
        (
            [id] => 3
            [name] => john
        )

    [3] => Array
        (
            [id] => 4
            [name] => robert
        )

)

$temp = array_unique(array_column($array, 'name'));
$unique_arr = array_intersect_key($array, $temp);

This will remove the duplicate names from array. unique by key

这将从数组中删除重复的名称。键唯一

回答by anghazi ghermezi

Just use SORT_REGULAR option as second parameter.

只需使用 SORT_REGULAR 选项作为第二个参数。

$uniqueArray = array_unique($array, SORT_REGULAR);

回答by r3wt

if you need to eliminate duplicates on specific keys, such as a mysqli id, here's a simple funciton

如果您需要消除特定键上的重复项,例如 mysqli id,这是一个简单的函数

function search_array_compact($data,$key){
    $compact = [];
    foreach($data as $row){
        if(!in_array($row[$key],$compact)){
            $compact[] = $row;
        }
    }
    return $compact;
}

Bonus PointsYou can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.

奖励积分您可以传递一组键并添加一个外部 foreach,但每个附加键会慢 2 倍。

回答by Anand agrawal

A very easy and logical way to Unique a multi dimension array is as follows,

唯一一个多维数组的一个非常简单和合乎逻辑的方法如下,

If you have array like this:

如果你有这样的数组:

Array
(
    [Key1] => Array
        (
            [0] => Value1
            [1] => Value2
            [2] => Value1
            [3] => Value3
            [4] => Value1
        )
    [Key2] => Array
        (
            [0] => Value1
            [1] => Value2
            [2] => Value1
            [3] => Value3
            [4] => Value4
        )
)

use foreachto solve this:

使用foreach来解决这个问题:

foreach($array as $k=>$v){
    $unique=array_unique($v);
    $array[$k]=$unique;
}

it will give you following result:

它会给你以下结果:

Array
(
    [Key1] => Array
        (
            [0] => Value1
            [1] => Value2
            [3] => Value3
        )
    [Key2] => Array
        (
            [0] => Value1
            [1] => Value2
            [3] => Value3
            [4] => Value4
        )
)

and if you want to rearrange the order of the keys,

如果你想重新排列键的顺序,

foreach($array as $k=>$v){
    $unique= array_values(array_unique($v));
    $array[$k]=$unique;
}

This operation will give you arranged key values like this:

此操作将为您提供如下排列的键值:

Array
(
    [Key1] => Array
        (
            [0] => Value1
            [1] => Value2
            [2] => Value3
        )
    [Key2] => Array
        (
            [0] => Value1
            [1] => Value2
            [2] => Value3
            [3] => Value4
        )
)

I hope this will clear everything.

我希望这会清除一切。