2013-09-28 79 views
1

我有以下數字數組($ data),我想將它分成兩個數組(range1和2)。陣列的分割序列號

我只是不會提前,因爲你可以看到。有人可以給我一個提示,我如何解決這個問題?

$data = array(16,17,18,19,20,23,24,25,26); 

$range1 = array(); 
$range2 = array(); 

$firstday = reset($data); 
$lastday = end($data); 

for($x = $firstday;$x <= $lastday; $x++){ 
    if($firstday == $x){ 
     $range1 =.$x;  
    } 
    elseif($x - $firstday == 1){ 
     $range2 =.$x; 
    } 
} 

Output must be array(16,17,18,19,20); array(23,24,25,26); 
+2

入住這裏http://php.net/manual/en/function .array-slice.php。此外,這看起來不正確'$ range1 =。 $ x'。你的意思是'$ range [] = $ x'? – elclanrs

+0

你需要什麼條件來拆分它們? – Deepak

+0

我正在嘗試製作日曆,並且$ data數組中的日期是佔用的數據。所以這些是2個時期,我想製作2個陣列。 – Bas

回答

3
$data = array(16,17,18,19,20,23,24,25,26); 
    $output1 = array_slice($data, 0, 5); 
    $output2 = array_slice($data, 5, 4); 
+0

是的,它!但我如何追蹤數字5和4? – Bas

+0

瀏覽PHP手冊,看到這裏http://php.net/manual/en/function.count.php – elclanrs

+0

這裏第二個參數是偏移量和第三個參數是長度&只要看看http://php.net /manual/en/function.array-slice.php也告訴@elclanrs –

0

通過@Jenson中號約翰用同樣的方法,

得到陣列的一半

$count = count($data); 
$output1 = array_slice($data, 0, ceil($count/2)); 
$output2 = array_slice($data, ceil($count/2), $count-(ceil($count/2))); 
+0

對不起我快。如果你有兩個時期,這將起作用。但是如果數組是數組(1,2,3,5,6,7,25,26,28);? – Bas

+0

@Bas上述數組的預期輸出是什麼? – Shafeeque

+0

對不起這個數組(1,2,3,5,6,7,25,26,28);必須是數組(1,2,3,5,6,7,25,26,27,28); $ output1 = array(1,2,3); $ output2 = array(5,6,7); $ output3 = array(25,26,27,28); – Bas