【问题标题】:How to traverse along an array to find the next filled value in PHP?如何遍历数组以在 PHP 中找到下一个填充值?
【发布时间】:2023-01-13 11:01:44
【问题描述】:

例如,在处理如下时间序列数据时:

[2022-07-10] => 38943
[2022-07-11] => 42259
[2022-07-12] => 45575
[2022-07-13] => null
[2022-07-14] => null
[2022-07-15] => 53845
[2022-07-16] => 57142

数据中可能存在一些“漏洞”。您可能会发现获取下一个或最后一个非空值很有用。

【问题讨论】:

    标签: php time-series


    【解决方案1】:

    以下函数将在数组中找到下一个“填充”值。

    • $data你要遍历的数组。
    • $from 您想要开始的索引。很可能,你是 使用这个函数循环。
    • $direction 方向可以用作 -1 作为最后一个或 +1 作为下一个。

    功能:

    // Traverse along an array in a specified direction to find the next value that is not null
    private function getnextFilledValue(array $data, int $from, int $direction) {
        for($offset = 1;; $offset++) {
            // Do not consider values outside of the array bounds
            // This could also be written within the second for condition
            if($offset < 0) return 0;
            if($offset >= count($data)) return null;
    
            // Calculate the offset taking the direction into account
            $directedOffset = $offset * $direction;
    
            // If a value is found, return it, otherwise continue traveling along the array
            if(!is_null($data[$from + $directedOffset])) {
                return $data[$from + $directedOffset];
            }
        }
    }
    

    您还可以更改 if(!is_null($da... 的条件以使用不同的检查来检测“已填充”值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2014-09-02
      • 2018-08-05
      • 2022-01-06
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 2019-06-06
      相关资源
      最近更新 更多