我有两个数组,如下所述:
$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");
我想获得不使用内置函数的$arr2
中不存在的那些元素。那么,我该怎么做呢?
答案 0 :(得分:1)
您可以循环两次,如果匹配则取消设置并中断内部循环
$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");
foreach($arr1 as $k => $v){
foreach($arr2 as $k1 => $v1){
if($v == $v1){
unset($arr1[$k]);break;
}
}
}
print_r($arr1);
Demo。
输出:
Array
(
[0] => 1
[3] => 6
)
答案 1 :(得分:1)
我对不使用PHP中的任何数组函数或特殊函数的问题很感兴趣,所以这是我想出的区别两个数组的方法(在编写它们时,没有进行进一步的测试如果不执行这些功能,则可能会破坏)。它需要一些杂耍:
$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");
$inTwo = array();
$notInTwo = array();
// get the matching elements from the two arrays to create a new array
foreach($arr1 AS $key => $val) {
foreach($arr2 AS $key2 => $val2) {
if($val == $val2) {
$inTwo[] = $val2;
}
}
}
print_r($inTwo);
$match = NULL; // variable used to hold match values, so they can be skipped
foreach($arr1 AS $key3 => $val3) {
foreach($inTwo AS $key4 => $val4) {
echo $val3 . ' ' . $val4 . "\n";
if(($val3 == $val4) || ($match == $val4)) { // test
echo "match\n";
$match = $val3; // set the new variable, to be checked on the next iteration
echo $match ."\n";
break;
} else {
$notInTwo[] = $val3;
break;
}
}
}
print_r($notInTwo);
以下是输出(所有测试输出留作参考):
Array //print_r($inTwo);
(
[0] => 3
[1] => 4
)
1 3
3 3
match // set the match variable
3
4 3 // skip this due to the match
match // set the match variable
4
6 3
Array print_r($notInTwo);
(
[0] => 1
[1] => 6
)
区分两个数组需要一些递归。如果您想知道这是如何工作的,可以查看PHP(以及提供差异算法的其他语言)的源代码,以了解如何执行此操作。我在这里写的是粗略的,是解决这个问题的公牛方法。
答案 2 :(得分:0)
您可以将array_walk
与in_array
一起使用
$r = [];
array_walk($arr1, function($v, $k) use (&$r, $arr2){
!in_array($v,$arr2) ? ($r[]=$v) : '';
});