2015-03-13 49 views
-1

有一個問題,我花了一些時間來找出解決方案。如何在數字範圍內找到可用的批次php

有一個主號碼批次。例如100-150(大小-51)。 並且該主批次中還有少量子批次。例如105 - 110和120 - 130.

我想在主批次中獲得其他批次及其批量大小。 例如 100-104,111-119和131-150

我試圖找到解決方案,但尚未找到任何解決方案。有沒有人可以指導我在php中做這個或給僞代碼,這對我會非常有幫助。

感謝

+1

也許如果你給一些真正的PHP數據結構的一些實際例子這將是我們更容易找出你的意思 – 2015-03-13 10:08:55

+0

請提供您想出或代碼應該如何呈現(組成代碼)。記住,我們不是自由工人。 ;) – 2015-03-13 10:08:57

+0

其實我想要一些指導來解決這個問題。其實我沒有任何想法來實現這一點。 – cha 2015-03-13 10:14:36

回答

1

使用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 
     ) 

) 
+0

有無論如何創建動態subBath數組並傳遞參數? – cha 2015-03-17 11:42:13

+0

@Cha你的意思是'array_diff'? – Sugar 2015-03-17 12:58:47

+0

是的。我可以創建subBatches的數組。但那些是動態數組。因此我試圖找到一種方法將它們作爲參數傳遞給array_diff。我剛纔找到了一個解決方案。 call_user_func_array('array_diff',$ this-> array_of_arrays);這是正確的方法嗎? – cha 2015-03-17 13:18:03

相關問題