'Get difference between two multidimensional arrays by comparing rows [duplicate]
I have two nested arrays and need to find the difference between the reference array and the data array. I am using array_dif_assoc function, and am unable to get the right difference, I am not sure why I am unable to get it. Could somebody help me out if I am doing some mistake or if I have to do it recursively;
$allCoursesAvailable = array(array('id'=>0,'name'=>'Select-One'), array('id'=>1,'name'=>'course1'),array('id'=>1,'name'=>'course2'),array('id'=>3,'name'=>'course3'));
$allCoursesforUser = array(array('id'=>0,'name'=>'Select-One'), array('id'=>1,'name'=>'course1'),array('id'=>4,'name'=>'course4'),array('id'=>5,'name'=>'course5'),array('id'=>6,'name'=>'course4'));
echo '<pre>';print_r(array_diff_assoc($allCoursesAvailable,$allCoursesforUser));
I am getting an empty array with this. When I use array_diff_assoc(), I should have got the arrays carrying course2 and course3, as they are not part of the 2nd array.
Am I missing some logic on the PHP end?
Solution 1:[1]
You should not use _assoc but the normal array_diff or array_intersect, because otherwise it will compare the ordering of the outer array and not just the content.
Also array_diff doesn't really work with subarrays, and you'd need a workaround:
print_r(
array_map("unserialize",
array_diff(
array_map("serialize", $allCoursesAvailable),
array_map("serialize", $allCoursesforUser)
)
)
);
Which would give you:
[2] => Array
(
[id] => 1
[name] => course2
)
[3] => Array
(
[id] => 3
[name] => course3
)
Not sure if that is what you wanted. And doing it manually might be advisable still.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mario |
