在数组中查找匹配或最接近的值 [英] Find a matching or closest value in an array

查看:116
本文介绍了在数组中查找匹配或最接近的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为给定的目标值搜索和查找数组中最接近的值?

How can I search and find, for a given target value, the closest value in an array?

假设我有这个示例数组:

Let's say I have this exemplary array:

array(0, 5, 10, 11, 12, 20)

例如,当我用目标值0搜索时,该函数应返回0;否则,该函数将返回0.当我搜索3时,它将返回5;当我用14搜索时,它将返回12.

For example, when I search with the target value 0, the function shall return 0; when I search with 3, it shall return 5; when I search with 14, it shall return 12.

推荐答案

将要搜索的数字作为第一个参数,将数字数组作为第二个参数:

Pass in the number you're searching for as the first parameter and the array of numbers to the second:

function getClosest($search, $arr) {
   $closest = null;
   foreach ($arr as $item) {
      if ($closest === null || abs($search - $closest) > abs($item - $search)) {
         $closest = $item;
      }
   }
   return $closest;
}

这篇关于在数组中查找匹配或最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆