开发者

comparing two Multi dimensional associative array s

I want to compare two arrays if an email address in array 1 exists in array 2 (here: uname1@email.com). In that case it should display that the email already exists.

$Array1 = Array
(        
[0] => Array
        (
  开发者_如何学运维          [username] => uname1
            [name] => fullname1
            [email] => uname1@email.com

        )
[1] => Array
        (
            [username] => uname2
            [name] => fullname2
            [email] => uname2@email.com    
        )
[2] => Array
        (
            [username] => uname3
            [name] => fullname3
            [email] => uname3@@email.com    
        )        
}   

$Array2 = Array
(    
[0] => Array
        (
            [username] => uname1
            [name] => fullname1
            [email] => uname1@email.com    
        )
}


You might want to consider using the email as the key. Something like this:

$a1 = array();
foreach ($Array1 as $v) $a1[$v['email']] = $v;

$a2 = array();
foreach ($Array2 as $v) $a2[$v['email']] = $v;

$intersection = array_values(array_intersect_key($a1, $a2));

This yields an array that contains all the values of the first array that have an email present in the second array. You can then iterate through that array to display error messages.


I would build an index of array 2 where the email address is the key:

$index = array();
foreach ($Array2 as $item) {
    $index[$item['email']] = true;
}

Then checking for an existing email address costs only O(1) for every item in array 1:

foreach ($Array1 as $item) {
    if (isset($index[$item['email']])) {
        echo 'email already exists';
    }
}


Pretty standard.

<?php
function userExists() {
    global $Array1, $Array2;
    for($Array2 as $user) {
        for($Array1 as $existingUser) {
            if($user['email'] == $existingUser['email']) {
                return true;
            }
        }
    }
    return false;
}
if(userExists())
    echo 'user exists.';
?>


Its easy.

$result = array_search($Array2[0], $Array1)
var_dump($result);

If you want to check whether something was found, remember to do it like this:

 if ($result !== false) { print "Found!"; }

The reason is that array_search can return integer 0, if result was found at index 0 in $Array1 and writing the check as

 if ($result == false) { print "Not found"; }

will print "Not found" in this case.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜