首页 > 解决方案 > 比较数组值并根据自定义值查找数组中的下一个值 (PHP)

问题描述

我正在尝试比较数组中的值并根据所选值选择数组中的下一个值。

例如

array(05:11,05:21,05:24,05:31,05:34,05:41,05:44,05:50,05:54);

例如,如果搜索值为05:34,则返回的值为05:41。如果值为05:5005:54则返回

我确实在这篇文章中找到了一些可能对我有帮助的东西,但是由于:我的价值观,它不起作用。

任何想法我怎样才能让它工作?

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

更新 也许我应该以某种方式将数组中的值转换为更方便在其中搜索的东西 - 只是一个想法。

标签: phparrayscompare

解决方案


使用内部指针数组迭代器——从性能的角度来看应该比 array_search 更好——你可以得到下一个值,如下所示:

$arr = array('05:11','05:21','05:24','05:31','05:34','05:41','05:44','05:50','05:54');
function getClosest($search, $arr) {

    $item = null;
    while ($key = key($arr) !== null) {
        $current = current($arr);
        $item = next($arr);
        if (
            strtotime($current) < strtotime($search) &&
            strtotime($item) >= strtotime($search)
        ) {
            break;
        } else if (
            strtotime($current) > strtotime($search)
        ) {
            $item = $current;
            break;
        }
    }

    return $item;
}

print_r([
    getClosest('05:50', $arr),
    getClosest('05:34', $arr),
    getClosest('05:52', $arr),
    getClosest('05:15', $arr),
    getClosest('05:10', $arr),
]);

这将输出: -

Array (
    [0] => 05:50
    [1] => 05:34
    [2] => 05:54
    [3] => 05:21
    [4] => 05:11
)

现场示例https://3v4l.org/tqHOC


推荐阅读