Why does array_diff on arrays of arrays return an empty array?
I've got two arrays, for which var_dump give the following values:
$array1:
Artifacts:array(2) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } [1]=> array(3) { [0]=> string(7) "module2" [1]=> string(17) "path/to/file2.txt" [2]=> string(0) "" } }
$array2:
开发者_开发问答Artifacts:array(1) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } }
I would think that doing array_diff($array1,$array2)
would give me an array countaining only the second elements. Instead I got an empty array. I try switching the parameters, and still an empty_array, but this time without surprise. Wouldn't array_diff
work on arrays of arrays?
From the documentation:
Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2
. In words: when the string representation is the same.
echo (string) array();
gives you just Array
, so for array_diff
, your arrays look like:
$array1 = array('Array', 'Array');
$array2 = array('Array');
So to create a diff for your arrays, you would need something like this (assuming that every element in the arrays is itself an array):
$diff = array();
foreach($array1 as $val1) {
$contained = false;
foreach($array2 as $val2) {
if(count(array_diff($val1, $val2)) == 0) {
$contained = true;
break;
}
}
if(!$contained) {
$diff[] = $val1;
}
}
Disclaimer: This is more or less just a sketch.
From the array_diff documentation.
This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);
From the array_diff manual page: "This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);."
Asked and answered here:
recursive array_diff()?
精彩评论