简体   繁体   English

根据当前键查找下一个非空数组值

[英]Finding the next non-empty array value, based on current key

I'm looking for an answer on something I've been literally spending my whole weekend on, and been struggling to find the right way to do it. 我一直在寻找整个周末都在寻找的答案,并且一直在努力寻找正确的方法来解决这个问题。

Say I have this PHP array: 说我有这个PHP数组:

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

The key for each row of this array is a day, based on the numeric representation of the day of the week (1 = Monday, 2 = Tuesday, etc.). 此数组每一行的键是一天,基于星期几的数字表示(1 =星期一,2 =星期二,等等)。

I want to get the value for today's day, but if it's empty, I want to get the next non-zero value. 我想获取今天的值,但是如果它为空,我想获取下一个非零值。 It also needs to reset back to Sunday (0) if Saturday (6) equals 0. 如果星期六(6)等于0,则还需要重置回星期日(0)。

Please help :S 请帮忙:S

<?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);
?>

Can you test this code and tell me if it's what you are looking for? 您可以测试此代码并告诉我它是否在找吗?

This code should be really easy to understand, but don't hesitate to ask me if you need some explanations. 这段代码应该很容易理解,但是请不要犹豫问我是否需要一些解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM