[英]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.