我想在两个不同的数组中找到唯一的值。例如,我有$srr1 =[1,3,7,10,13]和$arr2 =[7,4,1,5,3]。我遍历数组
foreach ($arr1 as $key1 => $val1) {
foreach ($arr2 as $key2 => $val2) {
if (isset($arr1[$val2]) && $ arr1[$val2] != $val1) {
echo "$arr1[$val2]"; // here I get 13 3 10 13 10 13 3 10 13 3 3 10, but 3 is superfluous here, because the number 3 is in both the first array and the second array.
}
}
}
你能告诉我如何解决这个问题吗?提前谢谢你。
有几种方法;这取决于你有多有创造力。这显示了三种方法:我喜欢的方法,一种符合您的标准的方法,最后一种相当非dry(不要重复自己)的过程方法,我不推荐。
前两者的工作方式几乎相同;第一个例子只是使用php内置函数在c中完成它。第二个例子不需要isset()
;你只是在迭代现有的数组键。
工作示例:http://sandbox.onlinephpfunctions.com/code/1488860430866c1e5c9428818753cf70b0258f26
<?php
$arr1 = [1,3,7,10,13];
$arr2 = [7,4,1,5,3];
function getUnique(array $a1, array $a2) : array
{
// initialize output
$unique = [];
foreach($a1 as $v) {
// ignore if present in other array
if(in_array($v, $a2)) { continue; }
$unique[] = $v;
}
return $unique;
}
print "Example 1n";
print_r(getUnique($arr1, $arr2));
print_r(getUnique($arr2, $arr1));
print "-----nn";
function getUnique2(array $a1, array $a2) : array
{
// initialize output
$unique = [];
foreach($a1 as $v) {
// for each iteration of outer array, initialize flag as not found
$foundInArray = false;
foreach($a2 as $v2) {
// if you find a match, mark it as so.
if($v == $v2) {
$foundInArray = true;
// (optional) no need to test the rest of the inner array
break;
}
}
// only store those not marked as found
if(!$foundInArray) {
$unique[] = $v;
}
}
return $unique;
}
print "Example 2n";
print_r(getUnique($arr1, $arr2));
print_r(getUnique($arr2, $arr1));
print "-----nn";
// or, a more obscure way
$flip = [];
foreach($arr1 as $v) {
// increment if we’ve seen this key before
if(array_key_exists($v, $flip)) {
$flip[$v]++;
// initialize if we haven’t
} else {
$flip[$v]=0;
}
}
// repeat code in a very wet way…
foreach($arr2 as $v) {
if(array_key_exists($v, $flip)) {
$flip[$v]++;
} else {
$flip[$v]=0;
}
}
foreach($flip as $k => $v) {
if($v==0) {
print "$kn";
}
}