在php中找到两个数组的差值

时间:2017-06-15 11:33:12

标签: php arrays

我希望从数组中获得差值,并且还希望比较该差异值来自哪个数组。

First Array =>变量:$ first_array

Array {607,608,609}

Second Array =>变量:$ second_array

Array {607,608,609,610}

希望获得像差值的输出:610 ......来自数组: - $ second_array

我怎么能得到?请帮帮我....

8 个答案:

答案 0 :(得分:1)

它会起作用

<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$result=array_diff($a,$b);
print_r($result);
?>

或者试试这个

<?php
 $array2 = array(607,608,609); 
 $array1 = array(607,608,609,275); 

foreach ($array1 as $value)
{ 
  if(in_array($value, $array2)) 
     { 
       $key = array_search($value, $array2); 
       $key1 = array_search($value, $array1); 
       unset($array2[$key]); 
       unset($array1[$key1]); 
      //echo "yes<br>"; 
      } 
  } 
     $merge = array_merge($array1,$array2); 
    print_r($merge);
 ?>

答案 1 :(得分:1)

尝试合并它们然后使用array_diff,array_diff_assoc和array_unique。
https://3v4l.org/Z1vpe

$first = Array(607,608,609,610);
$second = Array(800,607,608,609);
$Fcount = count($first);
$arr = array_merge($first, $second);


$arrc= array_diff($arr, array_diff_assoc($arr, array_unique($arr)));
foreach ($arrc as $key => $value){
    if($key < $Fcount){
        echo "first array ". $value . "\n";
    }else{
        echo "second array " . $value . "\n";
    }
}

编辑添加如何查找值所在的数组。https://3v4l.org/W7rch

答案 2 :(得分:1)

使用array_diff

<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$res=array_diff($a,$b);
print_r($res); // output 610
?>

答案 3 :(得分:1)

试试这个:

$first_array=array(607,608,609);
$second_array=array(607,608,609,610);

$result=calculate_diff($second_array,$first_array);
print_r($result);

function calculate_diff($array1,$array2)
{
    $diff = [];
    $larger_array = $array2;
    $smaller_array = $array1;

    if(count($array1) > count($array2))
    {
        $larger_array = $array1;
        $smaller_array = $array2;
    }

    foreach($larger_array as $ele)
    {
        if(!in_array($ele,$smaller_array))
        {
            $diff[] = $ele;
        }
    }

    return $diff;
}

答案 4 :(得分:0)

您可以使用array_diff()

$result=array_diff($first_array,$second_array);
print_r($result);

答案 5 :(得分:0)

试试这个:

$a = array(607,608,609,610);
$b = array(607,608,609);
$c = array_diff($a,$b);
print_r($c);

答案 6 :(得分:0)

试试这个:

$a1=array(607,608,609,610);
$a2=array(607,608,609);

$result=array_diff($a1,$a2);
print_r($result);

Output :-  Array ( [3] => 610 ) 

答案 7 :(得分:-2)

$ a1 = array(“ a” =>“红色”,“ b” =>“绿色”,“ c” =>“蓝色”,“ d” =>“黄色”); $ a2 = array(“ e” =>“ red”,“ f” =>“ green”,“ g” =>“ blue”,“ r” =>“ black”);

$ d = array_merge($ a1,$ a2);

output:array(“ a” =>“ red”,“ b” =>“ green”,“ c” =>“ blue”,“ d” =>“黄色”,“ e” =>“红色“,” f“ =>”绿色“,” g“ =>”蓝色“,” r“ =>”黑色“)

$ result = array_diff($ d,array_intersect($ a2,$ a1));

print_r($ result); output:array(“ d” =>“黄色”,“ r” =>“黑色”);