PHP中无数组相交的测试
我有以下代码:PHP中无数组相交的测试,php,Php,我有以下代码: $result = array_intersect($contacts1, $contacts2); 这将产生: Array ( [21] => [22] => [23] => [24] => [25] => [26] => [28] => 我有以下的if声明: if (empty($result)) { // i.e. NO INTERECTION 我刚刚意识到这不能作为无交叉点的测试,因为生成了许多元素,所有元素的
$result = array_intersect($contacts1, $contacts2);
这将产生:
Array
(
[21] =>
[22] =>
[23] =>
[24] =>
[25] =>
[26] =>
[28] =>
我有以下的if声明:
if (empty($result)) { // i.e. NO INTERECTION
我刚刚意识到这不能作为无交叉点的测试,因为生成了许多元素,所有元素的值都为null。鉴于此,测试两个数组的交集的最佳方法是什么?您可以检查所有值是否为空(如果您知道数组中不存在空值)。 您可以使用函数 例如:
$result = array_filter(array_intersect($contacts1, $contacts2));
这样,所有空值都将被删除,并且结果(如果不存在Interscion)将是一个空数组
更新:
如注释中所述,这也将删除非空值。
修订版将使用回调函数:
function filterOnlyNulls($elem) {
return $elem !== null;
}
$result = array_filter(array_intersect($contacts1, $contacts2), "filterOnlyNulls");
您可以检查所有值是否为null(如果您知道数组中不存在null)。 您可以使用函数 例如:
$result = array_filter(array_intersect($contacts1, $contacts2));
这样,所有空值都将被删除,并且结果(如果不存在Interscion)将是一个空数组
更新:
如注释中所述,这也将删除非空值。
修订版将使用回调函数:
function filterOnlyNulls($elem) {
return $elem !== null;
}
$result = array_filter(array_intersect($contacts1, $contacts2), "filterOnlyNulls");
如果数组中有空值,则
array\u intersect
将返回两个数组中的空值
$contacts1 = array("bob", "jane", NULL, NULL);
$contacts2 = array("jim", "john", NULL, NULL);
$result = array_intersect($contacts1, $contacts2);
print_r( $result );
排列
(
[2] =>
[3] =>
)
您可以使用array\u filter
在交叉点之前过滤每个阵列。它接受回调函数,但默认情况下,所有等于FALSE的条目都将被删除,包括null
$result2 = array_intersect(array_filter($contacts1), array_filter($contacts2));
print_r( $result2 );
排列
(
)
如果您想专门过滤空值,或者您的要求是什么,请使用
function mytest($val) {
return $val !== NULL;
}
$result3 = array_intersect(array_filter($contacts1, "mytest"), array_filter($contacts2, "mytest"));
print_r( $result3 );
排列
(
)
如果数组中有空值,则
array\u intersect
将返回两个数组中的空值
$contacts1 = array("bob", "jane", NULL, NULL);
$contacts2 = array("jim", "john", NULL, NULL);
$result = array_intersect($contacts1, $contacts2);
print_r( $result );
排列
(
[2] =>
[3] =>
)
您可以使用array\u filter
在交叉点之前过滤每个阵列。它接受回调函数,但默认情况下,所有等于FALSE的条目都将被删除,包括null
$result2 = array_intersect(array_filter($contacts1), array_filter($contacts2));
print_r( $result2 );
排列
(
)
如果您想专门过滤空值,或者您的要求是什么,请使用
function mytest($val) {
return $val !== NULL;
}
$result3 = array_intersect(array_filter($contacts1, "mytest"), array_filter($contacts2, "mytest"));
print_r( $result3 );
排列
(
)
谢谢你的信息,非常有用。谢谢你的信息,非常有用。