我需要将数据库值与post值进行比较。如果发布值(十进制价格)在2美分阈值内,则考虑值相等。结果是具有“真实”差异的数组。数组是一致的:相同数量的值,相同的键。
$db_values = array( "21" => 10.00, "22" => 20.00, "25" => 3.55);
$post_values = array( "21" => 9.98, "22" => 20.01, "25" => 2.55 );
我正在尝试将绝对值与我的容差值进行比较 - epsilon(Compare decimals in PHP)和array_udiff:
function epsilon_compare ($v1,$v2)
{
$epsilon = 0.02;
$diff = abs($v1 - $v2);
if ($diff <= $epsilon)
{
return 0;
//echo "numbers are equal";
} else {
return 1;
}
}
print_r(array_udiff($post_values, $db_values, "epsilon_compare"));
给出正确的结果:数组([25] =&gt; 2.55)
但是当我使用不同的数组时,我得到错误的结果,例如:
$db_values = array( "21" => 10.00, "22" => 20.00, "25" => 3.55);
$post_values = array( "21" => 8.00, "22" => 20.01, "25" => 2.55 );
在这种情况下,它给出:
Array ( [21] => 8 [22] => 20.01 [25] => 2.55 )
Key [22] =&gt;列出了20.01,但它在阈值范围内,因此不应该在结果集中。 我想我不完全理解array_udiff。感谢。
答案 0 :(得分:0)
我不认为udiff做你认为它做的事。如果您打印v1和v2,它将为您提供以下内容:
v1: 20.01 v2: 9.98
v1: 2.55 v2: 20.01
v1: 20 v2: 10
v1: 3.55 v2: 20
v1: 9.98 v2: 10
v1: 9.98 v2: 20.01
v1: 20.01 v2: 20
v1: 20.01 v2: 2.55
v1: 2.55 v2: 3.55
它比您想象的更具比较性。
您可能需要一段类似于以下内容的代码:
function compare_arrays($array1, $array2){
$result = array();
foreach($array1 as $value => $outcome){
if(epsilon_compare($array1[$value], $array2[$value])){
$result[$value] = $array2[$value];
}
}
return $result;
}
答案 1 :(得分:0)
http://docs.php.net/array_udiff:
用户提供的回调函数用于比较。如果第一个参数被认为分别小于,等于或大于第二个参数,则必须返回小于,等于或大于零的整数。如果元素不相等会导致不同(错误)的比较决策,那么你的函数总是返回1。
<?php
function epsilon_compare ($v1,$v2)
{
$epsilon = 0.02;
$diff = $v1 - $v2;
return abs($diff)<=$epsilon ? 0 : $diff;
}
$db_values = array( "21" => 10.00, "22" => 20.00, "25" => 3.55);
$post_values = array( "21" => 8.00, "22" => 20.01, "25" => 2.55 );
print_r(array_udiff($post_values, $db_values, "epsilon_compare"));
打印
Array
(
[21] => 8
[25] => 2.55
)
编辑:使用array_udiff_assoc
$db_values = array ( "1" => 7.55, "2" => 5.45, "3" => 5.45, "4" => 64.45, "5" => 54.75, "6" => 30.40, "7" => 56.99, "8" => 10.90, "9" => 60.85, "11" => 3.25, "12" => 13.05, "13" => 5.45, "14" => 8.00, "15" => 5.45, "16" => 13.05, "17" => 4.35 );
$post_values = array ( "1" => 7.55, "2" => 5.45, "3" => 5.45, "4" => 64.45, "5" => 54.75, "6" => 30.40, "7" => 56.99, "8" => 10.90, "9" => 60.85, "11" => 3.25, "12" => 13.05, "13" => 2.45, "14" => 8.00, "15" => 5.45, "16" => 12.05, "17" => 2.34 );
print_r(array_udiff_assoc($post_values, $db_values, "epsilon_compare"));
打印
Array
(
[13] => 2.45
[16] => 12.05
[17] => 2.34
)