如何在PHP中沿着一个数组以找到下一个填充值?

wljmcqd8  于 2023-01-16  发布在  PHP
关注(0)|答案(1)|浏览(136)

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

[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

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

z8dt9xmd

z8dt9xmd1#

下面的函数将查找数组中的下一个“填充”值。

  • $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...处的条件,以使用不同的检查来检测“填充”值。

相关问题