在php中的关联数组中删除具有重复值的数组

时间:2013-03-21 20:04:52

标签: php arrays

我有这个数组

$arr[] = array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'email@test.com', 'dm' => 'test');
$arr[] = array('id' => '2', 'fn' => 'Some2', 'ln' => 'Test2', 'email' => 'otheremail@test.com', 'dm' => 'test');
$arr[] = array('id' => '3', 'fn' => 'Some3', 'ln' => 'Test3', 'email' => 'email@test.com', 'dm' => 'test');

我想删除所有带有dublicate电子邮件的公开密钥$ arr [],以便只剩下这个:

$arr[] = array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'email@test.com', 'dm' => 'test');
$arr[] = array('id' => '2', 'fn' => 'Some2', 'ln' => 'Test2', 'email' => 'otheremail@test.com', 'dm' => 'test');

我在这里找到了不同的例子,但没有一个能解决我的问题。感谢

1 个答案:

答案 0 :(得分:0)

$arr = array(
    array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'email@test.com', 'dm' => 'test'),
    array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'other@test.com', 'dm' => 'test'),
    array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'email@test.com', 'dm' => 'test'),
    array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'email@test.com', 'dm' => 'test'),
    array('id' => '1', 'fn' => 'Some', 'ln' => 'Test', 'email' => 'other@test.com', 'dm' => 'test')
);

$checkEmail = array(); // restore email values

for($i=0;$i<count($arr);$i++){
    if (!in_array($arr[$i]['email'], $checkEmail)){ // check in each array if email value is unique
        print_r($arr[$i]); // if unique then output
    }
    $checkEmail[$i] = $arr[$i]['email']; // save email values
}

OUTPUT - &gt;

Array ( [id] => 1 [fn] => Some [ln] => Test [email] => email@test.com [dm] => test ) Array ( [id] => 1 [fn] => Some [ln] => Test [email] => other@test.com [dm] => test )