array( 'expected' =>-6ren">
gpt4 book ai didi

php - PHP的:array_intersect没有给出预期的结果

转载 作者:行者123 更新时间:2023-12-03 23:06:15 26 4
gpt4 key购买 nike

我正在尝试计算PHP数组中expectedactual之间的匹配,我有这个...

$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]

关于php - PHP的:array_intersect没有给出预期的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60205258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com