Finding Duplicate Values in Multi-dimensional Array

喜夏-厌秋 提交于 2020-01-25 20:28:10

问题


I have an array that looks similar to this:

Array
(
    [0] => Array
        (
            [0] => Model2345
            [1] => John Doe
            [2] => SN1234
        )

    [1] => Array
        (
            [0] => Model2345
            [1] => John Doe
            [2] => SN3456
        )

    [2] => Array
        (
            [0] => Model1234
            [1] => Jane Doe
            [2] => SN3456
        )
)

I want to have a way to check for duplicate values for keys [1] (the John Doe/Jane Doe key) and [2] (the SNxxxx key) in php, but ignore duplicates for key [0]. How can this be accomplished?


回答1:


Try this:

$array = your_array();

$current = current($array);
foreach($array as $key => $val){
 $duplicate[$key] = array_intersect($current, $val);
}

echo($duplicate);



回答2:


This question has already been answered here. The following is the code from the accepted answer of that question.

It utilizes the array_intersect() function.

<?php
$array = array(array("test data","testing data"), array("new data","test data"), array("another data", "test data", "unique data"));
$result = array();

$first = $array[0];
for($i=1; $i<count($array); $i++)
{
    $result = array_intersect ($first, $array[$i]);
    $first = $result;
}
print_r($result);
?>

OUTPUT:

Array ( [0] => test data )



来源:https://stackoverflow.com/questions/32218587/finding-duplicate-values-in-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!