我有一个多维数组:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
[1] => Array
(
[a] => 1
[b] => 5
[c] => 3
[d] => 4
)
[2] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
)
看看第一个索引(或零(和第三个索引(第二个索引(,a、b、c、d中的值等于1、2、3、4。假设数组是相等的,或者它们没有什么不同;我的问题是,我如何捕捉相等的数组,我的目的是向用户展示输入值的重复,
我已经在使用array_unique
了。这就是结果:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
[1] => Array
(
[a] => 1
[b] => 5
[c] => 3
[d] => 4
)
)
但我只想得到重复的数据,而不是删除重复的数据。
// first : get all data, if the data same / duplicate take only one data
$unique = array_unique($data, SORT_REGULAR);
// then, get the data which duplicate with
$diffCellUniq = array_diff_key($data, $unique);
// so print the result
print_r($diffCellUniq); exit;
Array
(
[2] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
)
// first : get all data, if the data same / duplicate take only one data
$unique = array_unique($data, SORT_REGULAR);
// then, get the data which duplicate with
$diffCellUniq = array_diff_key($data, $unique);
// so print the result
print_r($diffCellUniq); exit;
Array
(
[2] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
)
要只获取保留其密钥的重复项,请对array_keys
、array_fill_keys
、array_merge
、array_unique
和array_intersect_key
函数使用以下方法:
$dup_keys = [];
foreach ($arr as $item) { // $arr is your initial array
$keys = array_keys($arr, $item);
if (count($keys) > 1) {
$dup_keys = array_merge($dup_keys, $keys);
}
}
$dup_keys = array_unique($dup_keys);
$dup_items = array_intersect_key($arr, array_fill_keys($dup_keys, 0));
print_r($dup_items);
输出:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
[2] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
)
DEMO链接
由于array_unique在多维数组上不起作用,实现这一点的一种方法是序列化此数组并在其上应用array_unique。
一旦应用了唯一函数,我们就可以取消它的序列化,并将其恢复为数组格式。
参考:http://php.net/manual/en/function.array-unique.php#97285
试试这个:
$input = array_unique(array_map("serialize", $input))
$input = array_map("unserialize", $input);
您必须使用array_unique
:
$var = array_unique($YOUR ARRAY, SORT_REGULAR);
编辑:
<?php
$your_array = array (
0 => array
(
'a' => '1',
'b' => '2',
'c' => '3',
'd' => '4',
),
1 => array
(
'a' => '1',
'b' => '5',
'c' => '3',
'd' => '4',
),
2 => array
(
'a' => '1',
'b' => '2',
'c' => '3',
'd' => '4',
),
);
$tmpArray = array ();
foreach ($your_array as $row)
if (!in_array($row, $tmpArray)) array_push($tmpArray, $row);
var_dump($tmpArray);
?>
查看在线示例https://eval.in/631417