2013-10-04 11 views
0

我正在創建一個搜索算法,在文本文件中查找特定的字符串,並使用一個作爲起始點和一個作爲端點如何創建一個由if語句觸發的二維數組?

在其觸發函數來啓動線複製到一個數組起點,

function copy_line_to_array($line_to_copy, &$found_lines) 
    { 
    array_push($found_lines, $line_to_copy."<br>"); 
    } 

然後上,直到找到下一個開始點端點停止複印。

foreach($rows as $row => $data) 
    { 
    if(preg_match("/Start Point/", $data)) 
     { 
     //Set the copy trigger to on 
     $copy_line = "on"; 
     } 
    else if(preg_match("/End Point/", $data)) 
    { 
    //Turn off the copy trigger until we find another 'Start Point' 
    $copy_line = "off"; 
    //We also want to copy the 'End Point' line though 
    copy_line_to_array($data, $found_lines); 
    } 
    //If the trigger is set to on then call the function to copy the current line 
    if($copy_line == "on") 
    { 
    copy_line_to_array($data, $found_lines); 
    }   
} 

我想這樣做的是創建一個每個「起點」被發現時$ found_lines陣列內的陣列。這將允許我分別處理每個文本塊的開始和結束,並搜索它以獲取不同的字符串。

如何爲每個文本塊在數組中創建一個新數組?

回答

1

調整算法,使其將行復制到「當前塊」數組中。無論何時你發現和終點,追加當前塊的主,並啓動一個新問題:

$master = $chunk = []; 
$copy_line = false; 

foreach($rows as $row => $data) 
{ 
    if(preg_match("/Start Point/", $data)) 
    { 
     $copy_line = true; 
    } 
    else if(preg_match("/End Point/", $data)) 
    { 
     $copy_line = false; 
     copy_line_to_array($data, $chunk); 
     $master[] = $chunk; // append chunk to master 
     $chunk = [];   // start with fresh empty chunk next time 
    } 

    if($copy_line) 
    { 
     copy_line_to_array($data, $chunk); 
    }   
} 
+0

好吧,我試過,但沒有輸出。我在我的問題中包含了複製功能。該數組是否會推動這個數組的工作? – blarg

+0

@blarg:[Works for me](http://ideone.com/AuQ6IG)。 – Jon

+0

好,很好,它使用$ master = $ found_xml_lines = array();代替。我如何使用for-each語句解決每個$塊? – blarg

0
if($copy_line == "on") 
{ 
    $found_lines[] = $data 
}