如何在 php 的数字范围内找到可用的批次
How to find available batches inside of number range in php
有一个问题,我正在花一些时间找出解决方案。
有主号批次。例如 100 - 150(尺码 - 51)。
而且该主批次中的子批次也很少。例如 105 - 110 和 120 - 130。
我想在主批次中获取其他批次及其批次大小。
例如
100-104、111-119 和 131-150
我已尝试为此找到解决方案,但尚未找到任何解决方案。 php 有没有人可以指导我这样做或者给出伪代码,这对我很有帮助。
谢谢
使用array_diff
,您可以找到批次数组中的空闲空间。
然后从这个列表中提取不间断键的部分,从而留下每个自由范围。
$mainBatch = range(100, 150);
$subBatch = range(110, 120);
$subBatch2 = range(130,145);
$subBatchesFree = array_diff($mainBatch, $subBatch, $subBatch2);
$remainingBatches = array();
$i = 0;
foreach ($subBatchesFree as $key => $available) {
if (isset($subBatchesFree[$key + 1])) {
// Next key is still in the range
++$i;
} else {
// Next key is in a new range.
// I create the current one and init for the next range
$remainingBatches[] = range($subBatchesFree[$key - $i], $available);
$i = 0;
}
}
print_r($remainingBatches);
输出:
Array
(
[0] => Array
(
[0] => 100
[1] => 101
[2] => 102
[3] => 103
[4] => 104
[5] => 105
[6] => 106
[7] => 107
[8] => 108
[9] => 109
)
[1] => Array
(
[0] => 121
[1] => 122
[2] => 123
[3] => 124
[4] => 125
[5] => 126
[6] => 127
[7] => 128
[8] => 129
)
[2] => Array
(
[0] => 146
[1] => 147
[2] => 148
[3] => 149
[4] => 150
)
)
有一个问题,我正在花一些时间找出解决方案。
有主号批次。例如 100 - 150(尺码 - 51)。 而且该主批次中的子批次也很少。例如 105 - 110 和 120 - 130。
我想在主批次中获取其他批次及其批次大小。 例如 100-104、111-119 和 131-150
我已尝试为此找到解决方案,但尚未找到任何解决方案。 php 有没有人可以指导我这样做或者给出伪代码,这对我很有帮助。
谢谢
使用array_diff
,您可以找到批次数组中的空闲空间。
然后从这个列表中提取不间断键的部分,从而留下每个自由范围。
$mainBatch = range(100, 150);
$subBatch = range(110, 120);
$subBatch2 = range(130,145);
$subBatchesFree = array_diff($mainBatch, $subBatch, $subBatch2);
$remainingBatches = array();
$i = 0;
foreach ($subBatchesFree as $key => $available) {
if (isset($subBatchesFree[$key + 1])) {
// Next key is still in the range
++$i;
} else {
// Next key is in a new range.
// I create the current one and init for the next range
$remainingBatches[] = range($subBatchesFree[$key - $i], $available);
$i = 0;
}
}
print_r($remainingBatches);
输出:
Array
(
[0] => Array
(
[0] => 100
[1] => 101
[2] => 102
[3] => 103
[4] => 104
[5] => 105
[6] => 106
[7] => 107
[8] => 108
[9] => 109
)
[1] => Array
(
[0] => 121
[1] => 122
[2] => 123
[3] => 124
[4] => 125
[5] => 126
[6] => 127
[7] => 128
[8] => 129
)
[2] => Array
(
[0] => 146
[1] => 147
[2] => 148
[3] => 149
[4] => 150
)
)