1

I have two arrays both are two dimensional. I am comparing spreadsheet rows with DB rows. array key for both arrays are same.

array from DB fetch

$array1 = Array
(
[0] => Array
    (
        [uid] => 1
        [fname] => abc
        [lname] => deg
        [phone] => 123456789
    )
[1] => Array
    (
        [uid] => 2
        [fname] => jkl
        [lname] => xyz
        [phone] => 987654321
    )
[2] => Array
    (
        [uid] => 3
        [fname] => pqr
        [lname] => stu
        [phone] => 111111111
    )

array created from spreadsheet

$array2 = Array
(
[0] => Array
    (
        [uid] => 1
        [fname] => abc
        [lname] => deg
        [phone] => 4444444
    )
[1] => Array
    (
        [uid] => 3
        [fname] => pqr
        [lname] => stu
        [phone] => 111111111
    )
[2] => Array
    (
        [uid] => 4
        [fname] => aaa
        [lname] => bbb
        [phone] => 9999999
    )

Now I want only those key and value for specific user which are different.

For example : for uid=1, only phone should display. for uid=2, entire array should display. for uid=3, none(blank array) should display.

I have used array_diff() and it worked fine. but problem is that my code compare consequently (ir-respetive of uid). I want uid of array1 to be compare with uid of array2.

3
  • Do both arrays have the same number of sub-arrays? Commented Jun 25, 2013 at 8:16
  • count can be different in both arrays. Commented Jun 25, 2013 at 8:19
  • array1 can can have count 50. array2 can have count 45. keys will be always same for both array. I mean total 4 key(uid,fname,lanme,phone) for each sub-array. Commented Jun 25, 2013 at 8:25

1 Answer 1

2

I would reindex the arrays with the uid and then compare:

$new1 = array();
foreach ($array1 as $value){
    $new1[$value['uid']] = $value;
}
$new2 = array();
foreach ($array2 as $value){
    $new2[$value['uid']] = $value;
}
$diff = array();
foreach ($new1 as $key => $value){
    //compare $value with $new2[$key]
    if (isset($new2[$key])){
        $diff[$key] = array_diff($value, $new2[$key]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if I want to compare if email_id is same for both array instead of uid?
First, you'd have to include email_id in your arrays. Then you would check the diff array and see if there were any differences generated for email_id just the same as you would for phone or anything else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.