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

时间:2022-02-18 13:37:20

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
    )

)

17 个解决方案

#1


546  

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

#2


177  

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

从5.2.9开始,如果使用SORT_REGULAR标志,可以使用array_unique(),如下所示:

array_unique($array, SORT_REGULAR);

This makes the function compare elements for equality as if $a == $b were 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 documentation states:

不过,请记住,文件规定:

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

array_unique()不打算用于多维数组。

#3


49  

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

?>

#4


23  

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

#5


18  

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

kenrbnsn在rbnsn点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.

另一个Array_Unique应用于多分区数组。我只在两个分区的数组上测试过这个,但它可能会更一般化,或者使用递归。

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

这个函数使用序列化、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。

#6


10  

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
        )

)

#7


3  

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 Points You can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.

额外的好处是,你可以传递一个键的数组并添加一个外部foreach,但是每增加一个键会慢2x。

#8


2  

Just use SORT_REGULAR option as second parameter.

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

$uniqueArray = array_unique($array, SORT_REGULAR);

#9


2  

if you have an array like this:

如果你有这样一个数组:

(users is the name of the array)

(用户是数组的名称)

Array=>
 [0] => (array)
   'user' => 'john'
   'age' => '23'
 [1] => (array)
  'user' => 'jane'
  'age' => '20'
 [2]=> (array)
  'user' => 'john'
  'age' => '23'

and you want to delete duplicates...then:

你想删除重复的内容……

$serialized = array();
for ($i=0; $i < sizeof($users); $i++) { 
  $test = in_array($users['user'], $serialized);
    if ($test == false) {
      $serialized[] = $users['user'];
    }
 }

can be a solution :P

可以是解:P

#10


2  

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

这将删除数组中的重复名称。独特的关键

#11


1  

An easy to read solution, probably not the most efficient:

一个易于阅读的解决方案,可能不是最有效的:

function arrayUnique($myArray){
    if(!is_array($myArray))
        return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

} 

#12


1  

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 foreach to 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.

我希望这能把一切都弄清楚。

#13


0  

An alternative to serialize and unique

序列化和惟一的替代方法

$test = [
    ['abc','def'],
    ['ghi','jkl'],
    ['mno','pql'],
    ['abc','def'],
    ['ghi','jkl'],
    ['mno','pql'],
];

$result = array_reduce(
    $test,
    function($carry,$item){
        if(!in_array($item,$carry)) {
            array_push($carry,$item);
        }
        return $carry;
    },
    []
);

var_dump($result);

/*
 php unique.php
array(3) {
    [0] =>
        array(2) {
            [0] =>
                string(3) "abc"
            [1] =>
                string(3) "def"
        }
    [1] =>
        array(2) {
            [0] =>
                string(3) "ghi"
            [1] =>
                string(3) "jkl"
        }
    [2] =>
        array(2) {
              [0] =>
                  string(3) "mno"
              [1] =>
                  string(3) "pql"
        }
}

*/

* /

#14


0  

If you have an array like this

如果你有一个这样的数组

data = array
(
[0] => array
(
    [subject] => a
    [object] => c
),
[1] => array
(
    [subject] => b
    [object] => d
),
[2] => array
(
    [subject] => d
    [object] => b
),
[3] => array
(
    [subject] => d
    [object] => c
),
[4] => array
(
    [subject] => c
    [object] => a
),
[5] => array
(
    [subject] => c
    [object] => d
)
)

and you want to get arrays like this:

你想要这样的数组:

data = array
(
[0] => array
(
    [subject] => a
    [object] => c
),
[1] => array
(
    [subject] => b
    [object] => d
),
[2] => array
(
    [subject] => d
    [object] => c
)
)

or

data = array
(
[0] => array
(
    [subject] => d
    [object] => b
),
[1] => array
(
    [subject] => c
    [object] => a
),
[2] => array
(
    [subject] => c
    [object] => d
)
)

a following code can help

下面的代码可以帮助您

    $data1 = array();
    $data1 = $data;
    for($q=0;$q<count($data);$q++)
    {
            for($p=0;$p<count($data1);$p++)
            {
                    if (($data[$q]["subject"] == $data1[$p]["object"]) && ($data[$q]["object"] == $data1[$p]["subject"]))
                    {
                            $data1[$p]["subject"] = $data[$q]["subject"];
                            $data1[$p]["object"] = $data[$q]["object"];
                    }
            }
    }
    $data1 = array_values(array_map("unserialize", array_unique(array_map("serialize", $data1))));
    $data = $data1;

#15


0  

I've given this problem a lot of thought and have determined that the optimal solution should follow two rules.

我对这个问题做了很多思考,并确定最优解应该遵循两个规则。

  1. For scalability, modify the array in place; no copying to a new array
  2. 对于可伸缩性,请修改该数组;不复制到新数组
  3. For performance, each comparison should be made only once
  4. 对于性能,每次比较应该只进行一次

With that in mind and given all of PHP's quirks, below is the solution I came up with. Unlike some of the other answers, it has the ability to remove elements based on whatever key(s) you want. The input array is expected to be numeric keys.

考虑到这一点,并给出了所有PHP的特性,下面是我提出的解决方案。与其他一些答案不同,它可以根据需要的键删除元素。输入数组应该是数字键。

$count_array = count($input);
for ($i = 0; $i < $count_array; $i++) {
    if (isset($input[$i])) {
        for ($j = $i+1; $j < $count_array; $j++) {
            if (isset($input[$j])) {
                //this is where you do your comparison for dupes
                if ($input[$i]['checksum'] == $input[$j]['checksum']) {
                    unset($input[$j]);
                }
            }
        }
    }
}

The only drawback is that the keys are not in order when the iteration completes. This isn't a problem if you're subsequently using only foreach loops, but if you need to use a for loop, you can put $input = array_values($input); after the above to renumber the keys.

惟一的缺点是,当迭代完成时,键不是按顺序排列的。如果随后只使用foreach循环,那么这不是问题,但是如果需要使用for循环,可以输入$input = array_values($input);在上面把钥匙重新编号后。

#16


0  

As people are saying array_unique() is very slow, here is a snippet I use for one level multidimensional array.

正如人们所说的array_unique()非常慢,这里有一个我用于一级多维数组的片段。

$serialized_array = array_map("serialize", $input);

foreach ($serialized_array as $key => $val) {
     $result[$val] = true;
}

$output = array_map("unserialize", (array_keys($result)));

Reference first user contributed note of array_unique() function page in php.net

引用第一个用户在php.net中提供的array_unique()函数页面说明

#17


0  

Lots of person asked me how to make Unique multidimensional array. I have taken reference from your comment and it helps me.

很多人问我如何制作唯一的多维数组。我引用了你的评论,这对我很有帮助。

First of All, Thanks to @jeromegamez @daveilers for your solution. But every time i gave the answer, they asked me how this 'serialize' and 'unserialize' works. That's why i want to share the reason of this with you so that it will help more people to understand the concept behind this.

首先,感谢@jeromegamez @daveilers提供的解决方案。但每次我给出答案时,他们都问我这是如何“序列化”和“不序列化”的。这就是为什么我想和你们分享这个的原因,这样它将帮助更多的人理解背后的概念。

I am explaining why we use 'serialize' and 'unserialize' in steps :

我正在解释为什么我们在步骤中使用‘serialize’和‘unserialize’:

Step 1: Convert the multidimensional array to one-dimensional array

步骤1:将多维数组转换为一维数组

To convert the multidimensional array to a one-dimensional array, first generate byte stream representation of all the elements (including nested arrays) inside the array. serialize() function can generate byte stream representation of a value. To generate byte stream representation of all the elements, call serialize() function inside array_map() function as a callback function. The result will be a one dimensional array no matter how many levels the multidimensional array has.

要将多维数组转换为一维数组,首先生成数组中所有元素(包括嵌套数组)的字节流表示。函数的作用是:生成一个值的字节流表示形式。要生成所有元素的字节流表示,在array_map()函数中调用serialize()函数作为回调函数。结果将是一个一维数组,不管这个多维数组有多少层。

Step 2: Make the values unique

步骤2:使值惟一

To make this one dimensional array unique, use array_unique() function.

要使这个一维数组惟一,请使用array_unique()函数。

Step 3: Revert it to the multidimensional array

步骤3:将其还原为多维数组

Though the array is now unique, the values looks like byte stream representation. To revert it back to the multidimensional array, use unserialize() function.

虽然数组现在是唯一的,但是这些值看起来像字节流表示。要将其还原为多维数组,请使用unserialize()函数。

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

Thanks again for all this.

再次感谢你所做的一切。

#1


546  

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

#2


177  

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

从5.2.9开始,如果使用SORT_REGULAR标志,可以使用array_unique(),如下所示:

array_unique($array, SORT_REGULAR);

This makes the function compare elements for equality as if $a == $b were 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 documentation states:

不过,请记住,文件规定:

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

array_unique()不打算用于多维数组。

#3


49  

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

?>

#4


23  

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

#5


18  

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

kenrbnsn在rbnsn点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.

另一个Array_Unique应用于多分区数组。我只在两个分区的数组上测试过这个,但它可能会更一般化,或者使用递归。

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

这个函数使用序列化、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。

#6


10  

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
        )

)

#7


3  

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 Points You can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.

额外的好处是,你可以传递一个键的数组并添加一个外部foreach,但是每增加一个键会慢2x。

#8


2  

Just use SORT_REGULAR option as second parameter.

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

$uniqueArray = array_unique($array, SORT_REGULAR);

#9


2  

if you have an array like this:

如果你有这样一个数组:

(users is the name of the array)

(用户是数组的名称)

Array=>
 [0] => (array)
   'user' => 'john'
   'age' => '23'
 [1] => (array)
  'user' => 'jane'
  'age' => '20'
 [2]=> (array)
  'user' => 'john'
  'age' => '23'

and you want to delete duplicates...then:

你想删除重复的内容……

$serialized = array();
for ($i=0; $i < sizeof($users); $i++) { 
  $test = in_array($users['user'], $serialized);
    if ($test == false) {
      $serialized[] = $users['user'];
    }
 }

can be a solution :P

可以是解:P

#10


2  

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

这将删除数组中的重复名称。独特的关键

#11


1  

An easy to read solution, probably not the most efficient:

一个易于阅读的解决方案,可能不是最有效的:

function arrayUnique($myArray){
    if(!is_array($myArray))
        return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

} 

#12


1  

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 foreach to 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.

我希望这能把一切都弄清楚。

#13


0  

An alternative to serialize and unique

序列化和惟一的替代方法

$test = [
    ['abc','def'],
    ['ghi','jkl'],
    ['mno','pql'],
    ['abc','def'],
    ['ghi','jkl'],
    ['mno','pql'],
];

$result = array_reduce(
    $test,
    function($carry,$item){
        if(!in_array($item,$carry)) {
            array_push($carry,$item);
        }
        return $carry;
    },
    []
);

var_dump($result);

/*
 php unique.php
array(3) {
    [0] =>
        array(2) {
            [0] =>
                string(3) "abc"
            [1] =>
                string(3) "def"
        }
    [1] =>
        array(2) {
            [0] =>
                string(3) "ghi"
            [1] =>
                string(3) "jkl"
        }
    [2] =>
        array(2) {
              [0] =>
                  string(3) "mno"
              [1] =>
                  string(3) "pql"
        }
}

*/

* /

#14


0  

If you have an array like this

如果你有一个这样的数组

data = array
(
[0] => array
(
    [subject] => a
    [object] => c
),
[1] => array
(
    [subject] => b
    [object] => d
),
[2] => array
(
    [subject] => d
    [object] => b
),
[3] => array
(
    [subject] => d
    [object] => c
),
[4] => array
(
    [subject] => c
    [object] => a
),
[5] => array
(
    [subject] => c
    [object] => d
)
)

and you want to get arrays like this:

你想要这样的数组:

data = array
(
[0] => array
(
    [subject] => a
    [object] => c
),
[1] => array
(
    [subject] => b
    [object] => d
),
[2] => array
(
    [subject] => d
    [object] => c
)
)

or

data = array
(
[0] => array
(
    [subject] => d
    [object] => b
),
[1] => array
(
    [subject] => c
    [object] => a
),
[2] => array
(
    [subject] => c
    [object] => d
)
)

a following code can help

下面的代码可以帮助您

    $data1 = array();
    $data1 = $data;
    for($q=0;$q<count($data);$q++)
    {
            for($p=0;$p<count($data1);$p++)
            {
                    if (($data[$q]["subject"] == $data1[$p]["object"]) && ($data[$q]["object"] == $data1[$p]["subject"]))
                    {
                            $data1[$p]["subject"] = $data[$q]["subject"];
                            $data1[$p]["object"] = $data[$q]["object"];
                    }
            }
    }
    $data1 = array_values(array_map("unserialize", array_unique(array_map("serialize", $data1))));
    $data = $data1;

#15


0  

I've given this problem a lot of thought and have determined that the optimal solution should follow two rules.

我对这个问题做了很多思考,并确定最优解应该遵循两个规则。

  1. For scalability, modify the array in place; no copying to a new array
  2. 对于可伸缩性,请修改该数组;不复制到新数组
  3. For performance, each comparison should be made only once
  4. 对于性能,每次比较应该只进行一次

With that in mind and given all of PHP's quirks, below is the solution I came up with. Unlike some of the other answers, it has the ability to remove elements based on whatever key(s) you want. The input array is expected to be numeric keys.

考虑到这一点,并给出了所有PHP的特性,下面是我提出的解决方案。与其他一些答案不同,它可以根据需要的键删除元素。输入数组应该是数字键。

$count_array = count($input);
for ($i = 0; $i < $count_array; $i++) {
    if (isset($input[$i])) {
        for ($j = $i+1; $j < $count_array; $j++) {
            if (isset($input[$j])) {
                //this is where you do your comparison for dupes
                if ($input[$i]['checksum'] == $input[$j]['checksum']) {
                    unset($input[$j]);
                }
            }
        }
    }
}

The only drawback is that the keys are not in order when the iteration completes. This isn't a problem if you're subsequently using only foreach loops, but if you need to use a for loop, you can put $input = array_values($input); after the above to renumber the keys.

惟一的缺点是,当迭代完成时,键不是按顺序排列的。如果随后只使用foreach循环,那么这不是问题,但是如果需要使用for循环,可以输入$input = array_values($input);在上面把钥匙重新编号后。

#16


0  

As people are saying array_unique() is very slow, here is a snippet I use for one level multidimensional array.

正如人们所说的array_unique()非常慢,这里有一个我用于一级多维数组的片段。

$serialized_array = array_map("serialize", $input);

foreach ($serialized_array as $key => $val) {
     $result[$val] = true;
}

$output = array_map("unserialize", (array_keys($result)));

Reference first user contributed note of array_unique() function page in php.net

引用第一个用户在php.net中提供的array_unique()函数页面说明

#17


0  

Lots of person asked me how to make Unique multidimensional array. I have taken reference from your comment and it helps me.

很多人问我如何制作唯一的多维数组。我引用了你的评论,这对我很有帮助。

First of All, Thanks to @jeromegamez @daveilers for your solution. But every time i gave the answer, they asked me how this 'serialize' and 'unserialize' works. That's why i want to share the reason of this with you so that it will help more people to understand the concept behind this.

首先,感谢@jeromegamez @daveilers提供的解决方案。但每次我给出答案时,他们都问我这是如何“序列化”和“不序列化”的。这就是为什么我想和你们分享这个的原因,这样它将帮助更多的人理解背后的概念。

I am explaining why we use 'serialize' and 'unserialize' in steps :

我正在解释为什么我们在步骤中使用‘serialize’和‘unserialize’:

Step 1: Convert the multidimensional array to one-dimensional array

步骤1:将多维数组转换为一维数组

To convert the multidimensional array to a one-dimensional array, first generate byte stream representation of all the elements (including nested arrays) inside the array. serialize() function can generate byte stream representation of a value. To generate byte stream representation of all the elements, call serialize() function inside array_map() function as a callback function. The result will be a one dimensional array no matter how many levels the multidimensional array has.

要将多维数组转换为一维数组,首先生成数组中所有元素(包括嵌套数组)的字节流表示。函数的作用是:生成一个值的字节流表示形式。要生成所有元素的字节流表示,在array_map()函数中调用serialize()函数作为回调函数。结果将是一个一维数组,不管这个多维数组有多少层。

Step 2: Make the values unique

步骤2:使值惟一

To make this one dimensional array unique, use array_unique() function.

要使这个一维数组惟一,请使用array_unique()函数。

Step 3: Revert it to the multidimensional array

步骤3:将其还原为多维数组

Though the array is now unique, the values looks like byte stream representation. To revert it back to the multidimensional array, use unserialize() function.

虽然数组现在是唯一的,但是这些值看起来像字节流表示。要将其还原为多维数组,请使用unserialize()函数。

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

Thanks again for all this.

再次感谢你所做的一切。