【发布时间】:2020-05-29 00:13:44
【问题描述】:
我正在尝试计算 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'];
有人知道为什么顶级版本没有给我预期的结果吗?
【问题讨论】:
-
在第一种方法中,它将
expected的第二个4与actual的第二个4匹配。 -
来自手册:
array_intersect:“返回一个数组,其中包含 array1 中的所有值,其值存在于所有参数中。” -
也许你想要
array_intersect_assoc? -
我认为 array_intersect_assoc 可能是这个问题的答案。现在开始阅读
标签: php arrays array-intersect