【发布时间】:2019-04-27 02:15:10
【问题描述】:
我需要查看一个数组中的任何值是否存在于另一个数组中,并且数字是随机顺序的。当值的顺序不完全相同时,我发现解决方案似乎不起作用。
我尝试过array_intersect,但如果我要查找的号码不在同一顺序,这将不起作用。
$array1 = [1,2];
$array2 = [2,3];
$result = array_intersect($array1, $array2);
$result 返回 false,但我希望它意识到两个数组中都存在 2 并返回 true。
我想这有一个简单的解决方案,但找不到任何可行的方法。
更新:
这是完整的代码(使用 PHP,Laravel):
$student = User::find($id);
$studentLocations = $student->hospital()->pluck('id');
$preceptorLocations = Auth::user()->hospital()->pluck('id');
$result = array_intersect($studentLocations, $preceptorLocations);
if if 返回每个的结果:
[2] // studentLocations
[1,2] // preceptorLocations
但是,上面的完整代码我得到:
"array_intersect(): Argument #1 is not an array"
例如,如果我更改为array($student->hospital()->pluck('id')),它不会出错,不会返回true,当我只返回结果时,它们是这样的:
[[2]]
【问题讨论】:
-
您的代码运行良好。 3v4l.org/a7GKI
-
当我使用 if 语句时:'code' if ($result) { // do stuff } 'code' 它不起作用。
-
您发布的代码运行良好。如果您的代码确实有问题,请编辑您的帖子以包含该代码。
-
if(count($result)>0)? -
请提取minimal reproducible example。鉴于最近的编辑,您的问题也完全改变了,这表明前期准备不足。请接受tour 并阅读How to Ask 以获得指导!