2014-03-14 93 views
0

我試過到目前爲止:我有一個數組,如下圖所示,我想要做的是,創建一個基於價值BEGIN_DAY多個陣列:拆分數組基於值多發陣列 - PHP

Array 
(
    [0] => Array 
     (
      [0] => BEGIN_DAY 
      [1] => 15 
     ) 

    [1] => Array 
     (
      [0] => 20130701 
      [1] => 4 
      [2] => 4 
      [3] => 3060 
      [4] => 1 
     ) 

    [2] => Array 
     (
      [0] => 20130702 
      [1] => 270 
      [2] => 757 
      [3] => 13812810 
      [4] => 4 
     ) 

    [3] => Array 
     (
      [0] => 20130703 
      [1] => 5 
      [2] => 123 
      [3] => 3894971 
      [4] => 2 
     ) 

    [4] => Array 
     (
      [0] => 20130704 
      [1] => 290 
      [2] => 478 
      [3] => 5119617 
      [4] => 1 
     ) 
    [5] => Array 
     (
      [0] => END_DAY 
      [1] => 15 
     ) 
    [6] => Array 
     (
      [0] => BEGIN_DAY 
      [1] => 16 
     ) 
    [7] => Array 
     (
      [0] => 20130704 
      [1] => 290 
      [2] => 478 
      [3] => 5119617 
      [4] => 1 
     ) 

等等... 我想當過它BEGIN_DAY開始分裂這個陣列爲多個不同的陣列,所以它應該是這樣的: 第一:

Array 
(
    [0] => Array 
     (
      [0] => BEGIN_DAY 
      [1] => 15 
     ) 

    [1] => Array 
     (
      [0] => 20130701 
      [1] => 4 
      [2] => 4 
      [3] => 3060 
      [4] => 1 
     ) 

    [2] => Array 
     (
      [0] => 20130702 
      [1] => 270 
      [2] => 757 
      [3] => 13812810 
      [4] => 4 
     ) 

    [3] => Array 
     (
      [0] => 20130703 
      [1] => 5 
      [2] => 123 
      [3] => 3894971 
      [4] => 2 
     ) 

    [4] => Array 
     (
      [0] => 20130704 
      [1] => 290 
      [2] => 478 
      [3] => 5119617 
      [4] => 1 
     ) 
    [5] => Array 
     (
      [0] => END_DAY 
      [1] => 15 
     ) 

第二:

[0] => Array 
     (
      [0] => BEGIN_DAY 
      [1] => 16 
     ) 
    [1] => Array 
     (
      [0] => 20130704 
      [1] => 290 
      [2] => 478 
      [3] => 5119617 
      [4] => 1 
     ) 

我試過到目前爲止:

$days=array(); 
$split_by='BEGIN_DAY'; 
foreach ($day_all as $key => $value) { 
    if($day_all[$key][0]==$split_by){ 
     $days=array_slice($day_all, 0,$split_by); 
    } 
} 
var_dump($days); 

非常感謝!

+1

循環。每次你想重新格式化一個數組,一個循環就是你的選擇。不是一些隨機調用語法糖函數,而是一個內部直接和清晰邏輯的循環 –

回答

1
$sk = "first"; 
foreach ($array as $key=>$value) 
{ 
    if(in_array(BEGIN_DAY, $value)&&$key!=0) 
    { 
     $sk = "second"; 
    } 
    $result[$sk][] = $value; 
} 
echo "<pre>"; 
print_r($result); 
$first = $result['first']; 
$second = $result['second']; 
1

像這樣:

$yourArray = ...; //is your array as described above 
$finalArray = []; 
$tempArray = []; 
for($idx = 0; idx<$yourArray .length; idx++){ 
    $tempArray = $yourArray[$idx] 

    if($yourArray[$idx][0] == 'BEGIN_DAY'){ 
    $finalArray[] = $tempArray; 
    $tempArray = []; 
    } 
} 

最終陣列將包含陣列。每個BEGIN_DAY被發現的時候,該陣列將被插入到所述finalArray和一個新的被創建。 爲了改善代碼,請檢查單元是否存在,以避免索引異常。