简体   繁体   中英

How to create a two-dimensional array triggered from an if-statement?

I'm creating a search algorithm that looks for particular strings in a text file and uses one as a start point and one as an endpoint .

On the start point it triggers a function to start copying the lines to an array,

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

then on the endpoint to stop copying until it finds the next start point.

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);
    }           
}

What I would like to do is create an array within the $found_lines array each time a 'Start Point' is found. This will allow me to address each start to end block of text individually and search it for a different string.

How can I create a new array within an array for each block of text?

Adapt the algorithm so that it copies lines to a "current chunk" array instead. Whenever you find and end point, append the current chunk to the master array and start a new one:

$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
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM