1

I need to get difference between $array1 & $array2 based on StudentId column values.

 $array1 = array(
     array('StudentId' => 1),
     array('StudentId' => 2)
 );
 $array2 = array(
     array('StudentId' => 1)
);

The output should be:

Array ( [0] => Array ( [StudentId] => 2 ) )
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
KTAnj
  • 1,346
  • 14
  • 36

3 Answers3

3

Is this what you're looking for?

$array1 = array( array( 'StudentId' => 1 ), array( 'StudentId' => 2 ) );
$array2 = array( array( 'StudentId' => 1 ));

var_dump(array_diff_key($array1, $array2));

Output:

array(1) { [1]=> array(1) { ["StudentId"]=> int(2) } }

RhapX
  • 1,663
  • 2
  • 10
  • 17
  • 1
    `array_diff_key` check only the key and not the value. Since `$array1` has keys `[0], [1]` and `$array2` has keys `[0]` the result will always return the second key, regardless of its value. – Gil Jan 04 '15 at 06:55
  • @Gil Agreed, however, the OP did not ask to check values, but to get the difference between the two arrays. – RhapX Jan 04 '15 at 07:20
  • this is why I didn't call it a wrong answer, only wanted to point out this issue :) – Gil Jan 04 '15 at 07:29
  • @Gil I also agree with you. I need the way to compare value. – KTAnj Jan 11 '15 at 14:44
2

I solved this as following,

$array1 = array( array( 'StudentId' => 1 ), array( 'StudentId' => 2 ) );
$array2 = array( array( 'StudentId' => 1 ));
foreach($array1 as $a=>$val){
     if(in_array($val,$array2)){
          unset($array1[$a]);
     }
}

var_dump(array_values($array1));
KTAnj
  • 1,346
  • 14
  • 36
0

Take a look at http://php.net/manual/en/function.array-diff.php

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

Homberto
  • 165
  • 1
  • 4
  • 14
  • I tried `array_diff()` but then A PHP Error was encountered called **Array to string conversion** – KTAnj Jan 04 '15 at 06:33
  • If you're trying to `echo` or `print` the result, you will encounter an error because the return value is an array. Use `var_dump(array_diff($arr1, $arr2));` – Homberto Jan 04 '15 at 15:06
  • I tried `var_dump(array_diff($arr1, $arr2));`. It is also encounted that error – KTAnj Jan 11 '15 at 16:00
  • Perhaps change `$array1 = array( array( 'StudentId' => 1 ), array( 'StudentId' => 2 ) );$array2 = array( array( 'StudentId' => 1 ));` to `$array1 = array('StudentId' => 1, 'StudentId2' => 2);$array2 = array('StudentId' => 1);`, if possible. – Homberto Jan 11 '15 at 17:23
  • No It's not possible. :( – KTAnj Jan 12 '15 at 06:54