给定一个像这样的数组:
$array = array(
0 => array (
0 => 35,
1 => 30,
2 => 39
),
1 => array (
0 => 20,
1 => 12,
2 => 5
),
...
n => array (
0 => 10,
1 => 15,
2 => 7
),
);
我需要在数组中找到更接近给定参数的条目
find($a, $b, $c) {
//return the closer entry to the input
}
对于更接近的条目,我的意思是条目具有与输入中给出的值更接近的值,例如,传递(19,13,3)它应该返回$array [1]
我现在进行计算的方法是循环遍历整个数组,保持从-1开始的变量$distance和临时$result变量.对于每个元素,我计算距离
$dist = abs( subarray[0] - $a ) + abs ( subarray[1] - $b ) + abs( subarray[2] - $c )
如果计算出的距离等于-1或低于循环外的变量$distance,我将新距离分配给变量,并将相应的数组保存在$result变量中.在循环结束时,我最终得到了我需要的值.
此外,其中一个值可以为空:例如(19,13,false)仍应返回$array [1],然后计算应忽略缺失的参数 – 在这种情况下,距离计算为
$dist = abs( subarray[0] - $a ) + abs ( subarray[1] - $b );
忽略子阵列[2]和$c的值.
问题是,即使我的代码工作,也需要花费太多时间来执行,因为数组的大小很容易达到数十万个元素.我们仍然在谈论毫秒,但由于各种原因,这仍然是不可接受的.
有没有更有效的方法来进行此搜索以节省一些时间?
最佳答案 一个自定义功能 – 也许有一个更好的方法,但检查出来:
简而言之 :
搜索所有项目并以百分比查找它检查的数字($mArray [0 … 3])与您给出的数字之间的差异($mNumbersToFind [0 … 3].添加所有三个数字(每个元素)可能性 – 找到最大值 – 保持位置并返回数组.
$array = array(
array (
0 => 13,
1 => 15,
2 => 4
),
array (
0 => 20,
1 => 12,
2 => 5
),
array (
0 => 13,
1 => 3,
2 => 15
),
);
$mNumbersToFind = array(13,3,3);
$mFoundArray = find($mNumbersToFind, $array);
echo "mFinalArray : <pre>";
print_r($mFoundArray);
function find($mNumbersToFind, $mArray){
$mPossibilityMax = count($mNumbersToFind);
$mBiggestPossibilityElementPosition = 0;
$mBiggestPossibilityUntilNow = 0;
foreach($mArray as $index => $current){
$maxPossibility = 0;
foreach($current as $subindex => $subcurrent){
$mTempArray[$index][$subindex]['value'] = $subcurrent - $mNumbersToFind[$subindex];
$percentChange = (1 - $mTempArray[$index][$subindex]['value'] / $subcurrent) * 100;
$mTempArray[$index][$subindex]['possibility'] = $percentChange;
$maxPossibility += $percentChange/$mPossibilityMax;
}
$mTempArray[$index]['final_possibility'] = $maxPossibility;
if($maxPossibility > $mBiggestPossibilityUntilNow){
$mBiggestPossibilityUntilNow = $maxPossibility;
$mBiggestPossibilityElementPosition = $index;
}
}
echo "mTempArray : <pre>"; // Remove this - it's just for debug
print_r($mTempArray); // Remove this - it's just for debug
return $mArray[$mBiggestPossibilityElementPosition];
}
Debug Output ($mTempArray) :
mTempArray :
Array
(
[0] => Array
(
[0] => Array
(
[value] => 0
[possibility] => 100
)
[1] => Array
(
[value] => 12
[possibility] => 20
)
[2] => Array
(
[value] => 1
[possibility] => 75
)
[final_possibility] => 65
)
[1] => Array
(
[0] => Array
(
[value] => 7
[possibility] => 65
)
[1] => Array
(
[value] => 9
[possibility] => 25
)
[2] => Array
(
[value] => 2
[possibility] => 60
)
[final_possibility] => 50
)
[2] => Array
(
[0] => Array
(
[value] => 0
[possibility] => 100
)
[1] => Array
(
[value] => 0
[possibility] => 100
)
[2] => Array
(
[value] => 12
[possibility] => 20
)
[final_possibility] => 73.333333333333
)
)
Final Output :
mFinalArray :
Array
(
[0] => 13
[1] => 3
[2] => 15
)