PHP: Check for duplicate values in a multidimensional array

大兔子大兔子 提交于 2019-11-27 09:19:47

This will remove duplicate items from your array using array_unique():

$new_arr = array_unique($arr, SORT_REGULAR);

You can simply do it using in_array()

$data = Array(
    0 => Array("a", "b", "c"),
    1 => Array("x", "y", "z"),
    2 => Array("a", "b", "c"),
    3 => Array("a", "b", "c"),
    4 => Array("a", "x", "z"),
);

$final = array();
foreach ($data as $array) {
    if(!in_array($array, $final)){
        $final[] = $array;
    }
}

which will get you something like

array(3) {
  [0] => array(3) {
    [0] => string(1) "a"
    [1] => string(1) "b"
    [2] => string(1) "c"
  }
  [1] => array(3) {
    [0] => string(1) "x"
    [1] => string(1) "y"
    [2] => string(1) "z"
  }
  [2] => array(3) {
    [0] => string(1) "a"
    [1] => string(1) "x"
    [2] => string(1) "z"
  }
}

You can go smart with serialization for comparison of arrays.

var_dump(makeUnique($data));

function makeUnique(array $data)
{
    $serialized = array_map(create_function('$a', 'return serialize($a);'), $data);
    $unique = array_unique($serialized);
    return array_intersect_key($unique, $data);
}

Have fun

$arr = ...;
$final = array();
sort($arr);
foreach ($arr as $el) {
   if (!isset($prev) || $el !== $prev)
       $final[] = $el
    $prev = $el;
}

This is a more efficient1 solution (log n + n instead of quadratic) but it relies on a total order between all the elements of the array, which you may not have (e.g. if the inner arrays have objects).

1 More efficient than using in_array. Turns out array_unique actually uses this algorithm, so it has the same shortcomings.

Mrdexed

To check using array_unique on multidimensional arrays, you need to flatten it out like so, using implode.

    $c=count($array)
    for($i=0;$i<$c;$i++)
    {
    $flattened=implode("~",$array[$i]);
    $newarray[$i]=$flattened;
     }
    if(count(array_unique($newarray)
    <count($newarray))
    {
    //returns true if $array contains duplicates
    //can also use array_unique on $newarray 
    //to remove   duplicates, then explode, 
    //to return to default state
    }

Hope this is helpful, took sometime to get it.

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