比较php中的两个数组实例

时间:2014-04-17 11:19:26

标签: php arrays diff

我的脚本中有两个array个。

$array1 = array("a" =>'1','2','3','4','5','6','7','8','9','10');
$array2 = array("b" => '1','3','4','6','7','8','10');

我想比较这些数组并找到$array1但不存在于$array2中的项目。
为此,我使用了array_diff($array1, $array2),它提供了像Array ( [0] => 2 [3] => 5 [7] => 9 )这样的o / p 但我希望o / p像这样Array ( [0] => 2 [1] => 5 [2] => 9 )

4 个答案:

答案 0 :(得分:3)

尝试array_values

$output = array_values(array_diff($array1, $array2));

输出:

array (size=3)
  0 => string '2' (length=1)
  1 => string '5' (length=1)
  2 => string '9' (length=1)

答案 1 :(得分:2)

您可以使用sort()对差异后的数组进行排序。

$array1 = array("a" =>'1','2','3','4','5','6','7','8','9','10');
$array2 = array("b" => '1','3','4','6','7','8','10');
$diff = array_diff($array1, $array2);
sort($diff);

http://codepad.viper-7.com/yREvAg

或者像其他人一样,您可以使用array_values()

答案 2 :(得分:1)

使用array_diff

$array1 = array("a" =>'1','2','3','4','5','6','7','8','9','10');
$array2 = array("b" => '1','3','4','6','7','8','10');

$diff = array_diff($array1, $array2);

对于重置键,请使用array_values

$reset = array_values($diff);

答案 3 :(得分:0)

$temp = array_diff($array1, $array2)
$result = array();
foreach($temp as $key => $value){
     $result[] = $value;
}