【问题标题】:Compare array values and find next value in the array based on custom value (PHP)比较数组值并根据自定义值查找数组中的下一个值 (PHP)
【发布时间】:2019-02-28 18:54:40
【问题描述】:

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

例如

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

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

我确实在 this post 上找到了可能对我有帮助的东西,但由于我的值中有 :,它不会起作用。

有什么想法可以让它工作吗?

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

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

【问题讨论】:

  • 你应该把数组值用引号括起来
  • 因为这是字符串,所以 abs 不能按预期工作。也许您可以在执行 foreach 之前使用 strtotime (或类似的东西)将它们转换为更有意义的东西
  • 是的,这就是我编辑帖子时的想法。或者可能只是删除“:”,然后如果我输入 0535,它将返回 0541。这有意义吗?
  • @lStoilov 你只想得到给定值的下一项?
  • @Mohammad,是的,没错

标签: php arrays compare


【解决方案1】:

使用array_search(),您可以根据它的值找到数组项的索引。所以用它来获取搜索项的索引。

function getClosest($search, $arr) {
    return $arr[array_search($search, $arr)+1];
}

更新:

如果数组中不存在搜索值或搜索值是数组函数的最后一项,则返回空。

function getClosest($search, $arr) {
    $result = array_search($search, $arr);  
    return $result && $result<sizeof($arr)-1 ? $arr[$result+1] : "";
}

检查结果在demo

【讨论】:

  • 这很酷,但是如果您键入一个不在数组中的值怎么办。例如 05:35。然后就不行了
  • 如果值为05:54,则为未定义的偏移量!用条件包裹它。 :)
  • @Smartpal 已修复
【解决方案2】:

首先将您的数组值转换为字符串,因为您在值中使用了“:”,例如

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

然后使用下面的代码从数组中查找下一个值

function getClosest($search, $arr) {
  return $arr[array_search($search,$arr) + 1];
}

【讨论】:

  • 数组值中不允许冒号,这对这个问题很重要,您的答案中没有提到。
  • 我在评论中也提到过,并在我的演示中做了
  • 抱歉,我在发帖之前没有阅读您的评论,如果您愿意,我会提供我为这个问题制作的代码的屏幕截图 :) 这是找到价值的常见和最简单的技术在数组中。
【解决方案3】:

使用内部指针数组迭代器——从性能的角度来看应该比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

【讨论】:

  • 太好了。奇迹般有效。谢谢!
  • 我还更新了我的答案以处理小于数组中第一个元素的值。
猜你喜欢
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多