以下函数将在数组中找到下一个“填充”值。
-
$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... 的条件以使用不同的检查来检测“已填充”值。