1

I have some trouble to get the different array between 2 arrays

Array
(
[0] => Array
    (
        [CR_id] => 107
        [CR_label] => f
        [CR_question_id] => 54
        [CR_correct] => 1
    )

[1] => Array
    (
        [CR_id] => 121
        [CR_label] => C
        [CR_question_id] => 54
        [CR_correct] => 0
    )

)

And my second array

 Array
 (
[0] => Array
    (
        [CR_id] => 107
        [CR_label] => f
        [CR_question_id] => 54
        [CR_correct] => 1
    )

[1] => Array
    (
        [CR_id] => 117
        [CR_label] => B
        [CR_question_id] => 54
        [CR_correct] => 0
    )

[2] => Array
    (
        [CR_id] => 121
        [CR_label] => C
        [CR_question_id] => 54
        [CR_correct] => 0
    )

)

The result i wish to have is this :

Array(
    [0] => Array
    (
        [CR_id] => 117
        [CR_label] => B
        [CR_question_id] => 54
        [CR_correct] => 0
    )
  )

I saw functions like array_diff but I don't know how to apply it there because it's a 2 dimensional arrays. Is there a proper way to do that in a recursive method ?

TLR
  • 577
  • 3
  • 8
  • 24

3 Answers3

1

You could use array_udiff(), which allows you to define a custom comparison function:

array_udiff($array2, $array1, function(array $a, array $b) {
    return $b['CR_id'] - $a['CR_id'];
});
George Brighton
  • 5,131
  • 9
  • 27
  • 36
0

Simple use array_search and custom function:

Custom function:

function arrayDiffDemensial(&$firstArray, &$secondArray) {
    $resultDiff= array();
    foreach ($firstArray as $key => $value) {
        if (array_search($value, $secondArray) === false) {
           $resultDiff[$key] = $value;
        }
    }
    return $resultDiff;
}

Your arrays:

$firstArray= array(
    array('CR_id' => '107', 'CR_label'=> 'f', 'CR_question_id'=> 54, 'CR_correct'=> 1),
    array('CR_id' => '121', 'CR_label'=> 'C', 'CR_question_id'=> 54, 'CR_correct'=> 0),
);

$secondArray= array(
    array('CR_id' => '107', 'CR_label'=> 'f', 'CR_question_id'=> 54, 'CR_correct'=> 1),
    array('CR_id' => '117', 'CR_label'=> 'B', 'CR_question_id'=> 54, 'CR_correct'=> 0),
    array('CR_id' => '121', 'CR_label'=> 'C', 'CR_question_id'=> 54, 'CR_correct'=> 0),
);

$result = arrayDiffDemensial($secondArray , $firstArray);
var_dump($result);

Result:

 array(1) { [1]=> array(4) { ["CR_id"]=> string(3) "117" ["CR_label"]=> string(1) "B" ["CR_question_id"]=> int(54) ["CR_correct"]=> int(0) } } 
sergio
  • 5,210
  • 7
  • 24
  • 46
0

If you're looking at any difference and not just one value:

$result = array_map('unserialize', array_diff(
    array_map('serialize', $array2), array_map('serialize', $array1)));

print_r($result);  
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87