我正在尝试计算 PHP 数组中expected
和actual
之间的匹配项,我有这个......
$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'];
有人知道为什么顶级版本没有给我预期的结果吗?
因为它返回一个数组,其中包含array1 中的所有值,其值存在于所有参数中。
array_intersect(array $array1, array $array2[, array $... ]): array
https://www.php.net/manual/en/function.array-intersect.php
也许你可以从这个角度看清楚:
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]
计数实际上是正确的。
在您的第二个示例中不会发生这种情况,因为您使用数字 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)
}
}
它返回 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']));