2016-09-21 87 views
-1

我已經寫下面的代碼到所述陣列分成三個組塊/部分:拆分PHP數組成塊/部分通過定界符值

$data = [ 
    'SECTION1', 
    '1', 
    '2', 
    '3', 
    'SECTION2', 
    '4', 
    '5', 
    'SECTION3', 
    '6', 
    '7', 
    '8', 
]; 


$results = []; 


foreach ($data as $value) { 
    if(strpos($value, 'SECTION') !== false) { 
     array_push($results, []); 
    } else { 
     array_push($results[count($results)-1], $value); 
    } 
} 

這是結果:

$result = [ 
    [ 
     '1', 
     '2', 
     '3' 
    ], [ 
     '4', 
     '5' 
    ],[ 
     '6', 
     '7', 
     '8' 
    ] 
]; 

是否有一個更直觀,更可讀的方式來轉換這個數組與函數式編程方法?

回答

0
$data = [ 
    'SECTION1', 
    '1', 
    '2', 
    '3', 
    'SECTION2', 
    '4', 
    '5', 
    'SECTION3', 
    '6', 
    '7', 
    '8', 
]; 


$cnt = 0; 
$result = array(); 
foreach($data as $arr) { 
    if(strpos($arr, 'SECTION') !== false) { 
     $cnt++; 
    } else { 
     $result[$cnt][] = $arr; 
    } 
} 


echo "<pre>"; 
print_r($result); 

//修訂

Array 
(
    [1] => Array 
     (
      [0] => 1 
      [1] => 2 
      [2] => 3 
     ) 

    [2] => Array 
     (
      [0] => 4 
      [1] => 5 
     ) 

    [3] => Array 
     (
      [0] => 6 
      [1] => 7 
      [2] => 8 
     ) 

) 
0

檢查這一個更可讀和管理。

$data = [ 
    'SECTION1', 
    '1', 
    '2', 
    '3', 
    'SECTION2', 
    '4', 
    '5', 
    'SECTION3', 
    '6', 
    '7', 
    '8', 
]; 


$results = []; 


foreach ($data as $value) { 
    if(strpos($value, 'SECTION') !== false) { 
     $results[$value] = array(); 
    } else { 
     $keys = array_keys($results); 
     $last = end($keys); 
     $results[$last][] = $value; 
    } 
} 
echo '<pre>'; 
print_r($results); 
exit; 

出認沽將作爲

Array (
    [SECTION1] => Array 
     (
      [0] => 1 
      [1] => 2 
      [2] => 3 
     ) 

    [SECTION2] => Array 
     (
      [0] => 4 
      [1] => 5 
     ) 

    [SECTION3] => Array 
     (
      [0] => 6 
      [1] => 7 
      [2] => 8 
     ) 

)