开发者

Removing duplicate entries from an array with PHP

开发者 https://www.devze.com 2023-02-19 21:52 出处:网络
I have an array that looks like this when I use var_dump: array(4) { [0]=> array(2) { [0]=> string(1) \"1\"

I have an array that looks like this when I use var_dump:

array(4) {
  [0]=> array(2) { 
    [0]=> string(1) "1"
    ["userID"]=> string(1) "1" 
  }
  [1]=> array(2) {
    [0]=> string(1) "2" 
    ["userID"]=> string(1) "2"
  }
  [2]=> array(2) { 
    [0]=> string(1) "1"
    ["userID"]=> string(1) "1"
  } 
  [3]=> array(2) {
开发者_开发知识库    [0]=> string(1) "1"
    ["userID"]=> string(1) "1"
  }
}

That is 1,2,1,1

I tried using array_unique($arr) but on this particular array, instead of turning it into 1,2, it just turns the array into 1.

It should work, but I'm not sure why it doesn't.


array_unique only removes elements that are equal by their string value. That is not the case for sub-arrays.

You will need to iterate over the array manually (after sorting with a user function) and unset the doubles. Not pretty, sorry.


I am going to guess that all you care about is knowing which userIDs exist in the result set. Therefore, I will flatten the array first. After doing so, I can apply array_unique to obtain only the unique values. As others have stated, array_unique is not designed to work with multidimensional arrays.

$flattened = array_map(
  function($e) { return $e['userID']; },
  $array
);
$unique = array_unique($flattened);

If you like foreach loops, then it would look like this.

$flattened = array();
foreach ($array as $v) {
    $flattened[] = $v['userId'];
}
$unique = array_unique($flattened);

There is also an alternative to finding unique elements which offers a performance boost over array_unique -- O(n) time complexity versus O(nlogn). That is, array_unique($array) is equivalent to array_keys(array_flip($array)).


A kind of quick and dirty method might be to iterate over all elements, serialize the values and use these as keys in a new array that contains their values as well then use array_values() on that array like this:

<?php
function array_unique_recursive(array $a) {
    $result = array();
    foreach ($a as $item)
        $result[serialize($item)] = $item;
    return array_values($result);
}
?>


<?php
$arr = array(
               array ( 0=>"1",
                        userID=>"1"),
                array ( 0=>"2",
                        userID=>"2"),
        array ( 0=>"1",
                        userID=>"1"),
        array ( 0=>"1",
                        userID=>"1"));

    $arr_unique=array_unique($arr);
    echo '<pre>';
    var_dump($arr_unique);
    echo '</pre>';
?>


Try using sort regular filter ... <?php $arr = array_unique($arr, SORT_REGULAR); ?>

0

精彩评论

暂无评论...
验证码 换一张
取 消