首页 > 解决方案 > 如何在不使用内置函数的情况下在 php 中找到一个数组的缺失元素到另一个数组?

问题描述

我有两个数组,如下所述:

$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");

$arr2我想在不使用内置函数的情况下获取那些不在其中的元素。那么,我该怎么做呢?

标签: php

解决方案


我对在 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(以及其他提供差异算法的语言)的源代码,以了解如何做到这一点。我在这里写的是粗略的,一种在中国商店里牛逼的方法来解决这个问题。


推荐阅读