PHP:数组中的下一个可用值,以非索引值开头

Eri*_*ith 5 php arrays

我已经被困在这个PHP问题上大约一天了.基本上,我们有一个以24小时格式格式化的小时数组,以及一个任意值($hour)(也是一个24小时).问题是,我们需要获取$hour并获取数组中的下一个可用值,从立即开始的值开始$hour.

该数组可能类似于:

$goodHours = array('8,9,10,11,12,19,20,21).
Run Code Online (Sandbox Code Playgroud)

那么小时值可能是:

$hour = 14;
Run Code Online (Sandbox Code Playgroud)

因此,我们需要一些方法来了解19是下一个最佳时间.此外,我们可能还需要获得第二个,第三个或第四个(等)可用值.

问题似乎是因为14不是数组中的值,所以没有引用的索引可以让我们递增到下一个值.

为了使事情变得更简单,我已经$goodHours多次重复这些值,所以我没有必要回到开始(可能不是最好的方法,但快速修复).

我觉得这很简单,我很想念,但如果有人能说清楚,我会非常感激.

埃里克

Pas*_*TIN 4

您可以使用 for 循环来迭代数组,直到找到第一个大于您正在搜索的数组:

$goodHours = array(8,9,10,11,12,19,20,21);
$hour = 14;

$length = count($goodHours);
for ($i = 0 ; $i < $length ; $i++) {
    if ($goodHours[$i] >= $hour) {
        echo "$i => {$goodHours[$i]}";
        break;
    }   
}
Run Code Online (Sandbox Code Playgroud)

会给你:

5 => 19
Run Code Online (Sandbox Code Playgroud)



而且,要获取您正在搜索的项目以及之后的一些项目,您可以使用如下内容:

$goodHours = array(8,9,10,11,12,19,20,21);
$hour = 14;
$numToFind = 2;

$firstIndex = -1;
$length = count($goodHours);
for ($i = 0 ; $i < $length ; $i++) {
    if ($goodHours[$i] >= $hour) {
        $firstIndex = $i;
        break;
    }   
}

if ($firstIndex >= 0) {
    $nbDisplayed = 0;
    for ($i=$firstIndex ; $i<$length && $nbDisplayed<$numToFind ; $i++, $nbDisplayed++) {
        echo "$i => {$goodHours[$i]}<br />";
    }
}
Run Code Online (Sandbox Code Playgroud)

这会给你以下输出:

5 => 19
6 => 20
Run Code Online (Sandbox Code Playgroud)


基本上,这里的想法是:

  • 在数组中前进,直到找到>=您要查找的 第一项
    • 找到后退出第一个循环
  • 如果找到匹配的项目
    • 循环数组,直到其末尾,
    • 或者您已找到与您要找的一样多的物品。