php - 比较数组值并根据自定义值查找数组中的下一个值 (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:50
,05:54
则返回
我确实在这篇文章中找到了一些可能对我有帮助的东西,但是由于:
我的价值观,它不起作用。
任何想法我怎样才能让它工作?
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
更新 也许我应该以某种方式将数组中的值转换为更方便在其中搜索的东西 - 只是一个想法。
解决方案
使用内部指针数组迭代器——从性能的角度来看应该比 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
)
推荐阅读
- python - 从 pandas DataFrame 中切出唯一的行以存储在单独的 DataFrame 中
- python - 如何调整列表中多个图像的大小?
- aframe - 灯光不适用于 A-frame 0.9 中的 .gltf 模型(适用于 0.8)
- python - 在 SWI-Prolog 中实现哈希表
- javascript - 用数组中的元素替换字符“*”的实例 - JavaScript
- java - Java,我可以假设与层次结构的接口吗
- arduino - Arduino光敏电阻
- c++ - 对于列表排序,有没有办法让多个运算符重载具有相同的参数?
- docker - Bitnami/Express 4.16.4 - npm 安装
- amazon-web-services - 启动和关闭适用于 AWS ECS 或 Kubernetes 的实例?