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

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

问题描述

对于给定的目标值,如何搜索并找到数组中最接近的值?

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;当我用 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天全站免登陆