如果针是一个数组,我如何使用 in_array? [英] How can I use in_array if the needle is an array?

查看:22
本文介绍了如果针是一个数组,我如何使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆