How can I use in_array if the needle is an array?(如果针是一个数组,我如何使用 in_array?)
问题描述
我有 2 个数组,值将从数据库中加载,下面是一个示例:
I have 2 arrays, the value will be loaded from database, below is an example:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
我要做的是检查$arr1
中的所有值是否存在于$arr2
中.上面的例子应该是 TRUE
while:
What I want to do is to check if all the values in $arr1
exist in $arr2
. The above example should be a TRUE
while:
$arr3 = array(1,2,4,5,6,7);
比较 $arr1
与 $arr3
将返回 FALSE
.
comparing $arr1
with $arr3
will return a FALSE
.
通常我使用 in_array
因为我只需要将单个值检查到数组中.但在这种情况下,不能使用 in_array
.我想看看是否有一种简单的方法可以用最少的循环进行检查.
Normally I use in_array
because I only need to check single value into an array. But in this case, in_array
cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.
更新说明.
第一个数组将是一个包含唯一值的集合.第二个数组可以包含重复的值.在处理之前,它们都保证是一个数组.
First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.
推荐答案
使用 array_diff()
:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
// all of $arr1 is in $arr2
}
这篇关于如果针是一个数组,我如何使用 in_array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果针是一个数组,我如何使用 in_array?
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Laravel 仓库 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01