如何找到在一个PHP阵列的最佳匹配的密钥 [英] How to find the best matching key in a PHP array
本文介绍了如何找到在一个PHP阵列的最佳匹配的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在PHP关联数组。键是整数。我如何找到最近的钥匙任意整数输入?
I have an associative array in php. the keys are integers. how do i find the nearest key to any integer input?
推荐答案
简单,但强制的方法:
$distance = 1000000; // initialize distance as "far away"
foreach ($array as $idx => $value)
if (abs ($idx - $target_index) < $distance)
{
$distance = abs ($idx - $target_index);
$best_idx = $idx;
}
这篇关于如何找到在一个PHP阵列的最佳匹配的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文