[英]How to create a two-dimensional array triggered from an if-statement?
我正在創建一種搜索算法,該算法在文本文件中查找特定的字符串,並使用一個作為起點 ,使用一個作為端點 。
在起點,它觸發一個函數開始將線復制到數組中,
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數組中創建一個數組。 這將使我能夠分別解決文本的每個從頭到尾的塊,並在其中搜索不同的字符串。
如何為每個文本塊在數組中創建一個新數組?
調整算法,以便將行復制到“當前塊”數組中。 只要找到並結束,就將當前塊附加到主數組並開始一個新數組:
$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);
}
}
if($copy_line == "on")
{
$found_lines[] = $data
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.