我试图从2个数组中获得差异。但我很难做到这一点。
$test1 = array();
$test2 = array();
$sizeUniqMembers1 = sizeof($test1);
$sizeUniqMembers2 = sizeof($test2);
print_r($test1);
print_r($sizeUniqMembers1);
我的test1输出:有50个元素。
Array ( [47457] => 4 [32089] => 16 [47555] => 1 [38479] => 15 [47641] => 1 [38601] => 3 [38619] => 3 [38493] => 1 [38458] => 1 [47644] => 5 [37545] => 8 [47632] => 3 [47330] => 1 [41088] => 2 [47499] => 4 [47502] => 2 [47617] => 5 [38556] => 5 [47520] => 2 [47611] => 3 [38639] => 1 [47523] => 3 [38582] => 9 [43198] => 1 [38544] => 1 [47483] => 1 [47458] => 2 [47504] => 2 [36165] => 1 [36858] => 8 [38658] => 1 [38436] => 1 [38656] => 2 [47479] => 1 [38611] => 4 [47585] => 2 [47407] => 1 [47332] => 1 [38655] => 1 [47497] => 1 [43199] => 1 [41141] => 1 [47584] => 3 [47472] => 9 [47541] => 2 [47530] => 1 [47582] => 2 [47452] => 4 [38635] => 3 [41107] => 1 )
print_r($test2);
print_r($sizeUniqMembers2);
我的test2输出:有89个元素。
Array ( [47457] => 4 [32089] => 61 [47555] => 5 [38479] => 65 [47641] => 1 [38601] => 7 [38619] => 9 [38493] => 12 [38458] => 3 [47644] => 5 [37545] => 35 [47632] => 8 [47330] => 4 [41088] => 4 [47499] => 6 [47502] => 6 [47617] => 10 [38556] => 10 [47520] => 2 [47611] => 12 [38639] => 5 [47523] => 12 [38582] => 53 [43198] => 3 [38544] => 1 [47483] => 7 [47458] => 12 [47504] => 3 [36165] => 2 [36858] => 20 [38658] => 1 [38436] => 1 [38656] => 5 [47479] => 2 [38611] => 7 [47585] => 2 [47407] => 2 [47332] => 5 [38655] => 12 [47497] => 10 [43199] => 1 [41141] => 2 [47584] => 18 [47472] => 31 [47541] => 8 [47530] => 2 [47582] => 11 [47452] => 7 [38635] => 14 [41107] => 6 [41149] => 6 [38585] => 4 [41100] => 8 [38652] => 3 [37747] => 3 [47331] => 11 [47620] => 5 [47533] => 2 [47448] => 2 [47615] => 2 [384] => 1 [37206] => 4 [43159] => 1 [47460] => 6 [38584] => 1 [37146] => 1 [47521] => 1 [36599] => 1 [47531] => 1 [38462] => 3 [38651] => 7 [38451] => 2 [36333] => 5 [38452] => 1 [47495] => 1 [38554] => 3 [43175] => 6 [38501] => 6 [38576] => 2 [47323] => 1 [38612] => 1 [38489] => 5 [36110] => 1 [47410] => 1 [38437] => 1 [47490] => 1 [37219] => 2 [47540] => 1 [38430] => 1 )
这将剩下39个元素。所以我使用的是array_diff
$new_array = array_diff($test2,$test1);
$sizenew_array = sizeof($new_array);
print_r($new_array);
但声明只给了我30个元素,其中一些甚至不同。为什么会发生这种情况
这是我对new_array的输出:
Array ( [32089] => 61 [38479] => 65 [38601] => 7 [38493] => 12 [37545] => 35 [47499] => 6 [47502] => 6 [47617] => 10 [38556] => 10 [47611] => 12 [47523] => 12 [38582] => 53 [47483] => 7 [47458] => 12 [36858] => 20 [38611] => 7 [38655] => 12 [47497] => 10 [47584] => 18 [47472] => 31 [47582] => 11 [47452] => 7 [38635] => 14 [41107] => 6 [41149] => 6 [47331] => 11 [47460] => 6 [38651] => 7 [43175] => 6 [38501] => 6 )
答案 0 :(得分:2)
array_diff()适用于VALUES,并忽略KEYS。 e.g。
php > $x = array(10 => 1, 100 => 2);
php > $y = array(3 => 1);
php > var_dump(array_diff($x, $y));
array(1) {
[100]=>
int(2)
}
仅返回2
值,因为$ y数组中没有2
。但请注意1
不会作为差异返回,因为它存在于两个数组中,即使其对应的键不同。