php multi-dimensional array remove duplicate

2019-01-01 15:55发布

Not sure if this question is a duplicate in need of removal, but I couldn't find the answer elsewhere so I'll have a go at asking.

I've got a 2d array that looks as follows:

Array
(
[0] => Array
    (
        [0] => dave
        [1] => jones
        [2] => c@b.c
    )

[1] => Array
    (
        [0] => john
        [1] => jones
        [2] => a@b.c

    )

[2] => Array
    (
        [0] => bruce
        [1] => finkle
        [2] => c@b.c
    )
)

I'd like to remove those with duplicate emails. So in the above example I'd like to just remove either [][0] or [][2]. I'm not worried about checking against names or anything like that, I just need the sub arrays to be deduplicated based on a single value.

At the moment I have something like this

  if(is_array($array) && count($array)>0){
  foreach ($array as $subarray) {
    $duplicateEmail[$subarray[2]] = isset($duplicateEmail[$subarray[2]]);
    unset($duplicateEmail[$subarray[2]]);
   }
  }

but it just ain't right. Any help appreciated.

7条回答
步步皆殇っ
2楼-- · 2019-01-01 16:50

My proposition:

protected function arrayUnique($array, $preserveKeys = false)
{
    $uniqueArray = array();
    $hashes = array();

    foreach ($array as $key => $value) {
        if (true === is_array($value)) {
            $uniqueArray[$key] = $this->arrayUnique($value, $preserveKeys);

        } else {
            $hash = md5($value);

            if (false === isset($hashes[$hash])) {
                if ($preserveKeys) {
                    $uniqueArray[$key] = $value;
                } else {
                    $uniqueArray[] = $value;
                }

                $hashes[$hash] = $hash;
            }
        }
    }

    return $uniqueArray;
}
查看更多
登录 后发表回答