PHP:检查一个数组是否包含另一个数组中的所有数组值
$all = array
(
0 => 307,
1 => 157,
2 => 234,
3 => 200,
4 => 322,
5 => 324
);
$search_this = array
(
0 => 200,
1 => 234
);
我想找出是否包含所有值并返回或.有什么想法吗?$all
$search_this
true
false
$all = array
(
0 => 307,
1 => 157,
2 => 234,
3 => 200,
4 => 322,
5 => 324
);
$search_this = array
(
0 => 200,
1 => 234
);
我想找出是否包含所有值并返回或.有什么想法吗?$all
$search_this
true
false
前面的答案都做了比他们需要的更多的工作。只需使用array_diff。这是最简单的方法:
$containsAllValues = !array_diff($search_this, $all);
这就是你所要做的。
$containsSearch = count(array_intersect($search_this, $all)) === count($search_this);
或者对于关联数组,请查看array_intersect_assoc())。
或者,对于子数组的递归比较,请尝试:
<?php
namespace App\helpers;
class Common {
/**
* Recursively checks whether $actual parameter includes $expected.
*
* @param array|mixed $expected Expected value pattern.
* @param array|mixed $actual Real value.
* @return bool
*/
public static function intersectsDeep(&$expected, &$actual): bool {
if (is_array($expected) && is_array($actual)) {
foreach ($expected as $key => $value) {
if (!static::intersectsDeep($value, $actual[$key])) {
return false;
}
}
return true;
} elseif (is_array($expected) || is_array($actual)) {
return false;
}
return (string) $expected == (string) $actual;
}
}