PHP:array_intersect未给出预期结果
我试图在PHP数组中计算PHP:array_intersect未给出预期结果,php,arrays,array-intersect,Php,Arrays,Array Intersect,我试图在PHP数组中计算预期的和实际的之间的匹配,我有这个 $array = array( "item" => array( 'expected' => array( '1' => 25, '2' => 4, '3' => 4, ), 'color' => 'red', 'actual' => array(
预期的
和实际的
之间的匹配,我有这个
$array = array(
"item" => array(
'expected' => array(
'1' => 25,
'2' => 4,
'3' => 4,
),
'color' => 'red',
'actual' => array(
'1' => 25,
'2' => 4,
'3' => 3,
),
),
);
foreach ($array as $key => $arrayItem) {
$matches = array (
'matches' => count ( array_intersect ( $arrayItem['expected'], $arrayItem['actual'] ) ),
);
}
echo "Matches = " . $matches['matches'];
我希望它返回2
,但实际上它返回3
。如果我像下面的例子中那样更改值,那么它确实有效
$array = array(
"item" => array(
'expected' => array(
'1' => 25,
'2' => 84,
'3' => 4,
),
'color' => 'red',
'actual' => array(
'1' => 25,
'2' => 84,
'3' => 3,
),
),
);
foreach ($array as $key => $arrayItem) {
$matches = array (
'matches' => count ( array_intersect ( $arrayItem['expected'], $arrayItem['actual'] ) ),
);
}
echo "Matches = " . $matches['matches'];
有人知道为什么顶级版本没有给我预期的结果吗?计数实际上是正确的。
在第二个示例中不会出现这种情况,因为您使用的是数字84和4,但基本上这里是匹配项:
$arrayItem['expected'][1]
与$arrayItem['actual'][1]
匹配(25和25)
$arrayItem['expected'][2]
与$arrayItem['actual'][2]
匹配(4和4)
$arrayItem['expected'][3]
与$arrayItem['actual'][2]
匹配(4和4)
3的计数是正确的
您可以通过将代码更改为以下内容来测试这一点:
$matches = array(
'matches' => array_intersect ($arrayItem['expected'], $arrayItem['actual'])
);
var_dump($matches);
array(1) {
["matches"] => array(3) {
[1]=> int(25)
[2]=> int(4)
[3]=> int(4)
}
}
在这里您将看到以下输出:
$matches = array(
'matches' => array_intersect ($arrayItem['expected'], $arrayItem['actual'])
);
var_dump($matches);
array(1) {
["matches"] => array(3) {
[1]=> int(25)
[2]=> int(4)
[3]=> int(4)
}
}
因为它返回一个数组,该数组包含数组1中的所有值,其值存在于所有参数中
array\u intersect(array$array1,array$array2[,array$…]):array
也许你可以从这个角度看得很清楚:
var_dump(array_intersect([25, 4, 4, 4], [25, 4, 3])); // [25, 4, 4, 4]
// because the number `4` is in the second array!
var_dump(array_intersect([25, 4, 3], [25, 4, 4, 4])); // [25, 4]
它返回2
<?php
$array = array(
"item" => array(
'expected' => array(
'1' => 25,
'2' => 84,
'3' => 4,
),
'color' => 'red',
'actual' => array(
'1' => 25,
'2' => 84,
'3' => 3,
),
),
);
echo count(array_intersect($array['item']['expected'],$array['item']['actual']));
在第一种方法中,它将预期的的第二个4
与实际的的第二个4
相匹配。从手册:array\u intersect
:“返回包含array1中所有值的数组,其值存在于所有参数中。”也许你想要array\u intersect\u assoc
?我想array\u intersect\u assoc可能就是这个问题的答案。现在读起来就知道了。他的问题是为什么第一种方法是3
。$arrayItem['expected'][2]和$arrayItem['expected'][3]被视为不匹配。数字4
在expected
中满足两次,这就是为什么4
在actual
中检查两次,当然会得到匹配。没有什么能与自己相匹配。