【问题标题】:Finding the next non-empty array value, based on current key根据当前键查找下一个非空数组值
【发布时间】:2015-07-28 01:22:36
【问题描述】:

我正在寻找我整个周末都在做的事情的答案,并且一直在努力寻找正确的方法。

假设我有这个 PHP 数组:

Array (
    [0] => 0
    [1] => 182
    [2] => 185
    [3] => 0
    [4] => 187
    [5] => 0
    [6] => 0
)

此数组每一行的键是一天,基于星期几的数字表示(1 = 星期一,2 = 星期二等)。

我想获取今天的值,但如果它为空,我想获取下一个非零值。如果星期六 (6) 等于 0,它还需要重置回星期日 (0)。

请帮忙:S

【问题讨论】:

    标签: php arrays key


    【解决方案1】:
    <?php
    $day = date('w'); // Getting today day number
    $myArray = [0, 182, 185, 0, 187, 0, 0]; // Your array
    
    
    
    function getValue($day, $myArray){
    
        $loopCount = 0; // avoid infinite loop
    
        for($i = $day; $i <= 7; $i++){
    
            // $i == 7 <=> $i = 0
            if($i == 7){
                $i = 0;
            }
    
            // Check if the value can be returned
            if($myArray[$i] != 0){
                return $myArray[$i];
            }
    
    
            $loopCount++;
    
            // If we have checked the whole array, we return null
            if($loopCount == 7){
                return null;
            }
        }
    }
    
    echo getValue($day, $myArray);
    ?>
    

    你能测试一下这段代码并告诉我它是否是你要找的吗?

    这段代码应该很容易理解,但如果你需要一些解释,请随时问我。

    【讨论】:

    • 宾果游戏!非常感谢维科!非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2022-01-07
    • 2022-10-25
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多