php - 如何在不使用内置函数的情况下在 php 中找到一个数组的缺失元素到另一个数组?
问题描述
我有两个数组,如下所述:
$arr1 = array("1","3","4","6");
$arr2 = array("2","3","4","5","7");
$arr2
我想在不使用内置函数的情况下获取那些不在其中的元素。那么,我该怎么做呢?
解决方案
我对在 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(以及其他提供差异算法的语言)的源代码,以了解如何做到这一点。我在这里写的是粗略的,一种在中国商店里牛逼的方法来解决这个问题。
推荐阅读
- php - 无论输入如何,如何使用 preg_replace?
- python - 如何在 log-log sns.regplot 中实现直线回归线?
- c# - 如何加载网站,然后在 Asp.Net Core (C#) Razor Pages 中添加数据
- java - 讲解base64图像显示
- reactjs - React useState - FaStar 图标 - 单击以更改和更改回
- python - Django中的名称错误-视图函数中的嵌套函数-保存到数据库
- python - 将基于 exec() 的 Python 代码转换为 iPython API
- angular - 关于 cookie、JWT 和 Web 应用程序
- javascript - ReactJS FilePond - 上传到一个 FilePond 组件会清除同一页面中其他 FilePond 组件中的状态
- java - 在java中使用循环按顺序输出数字