duanhe1976 2013-10-04 09:05
浏览 34
已采纳

如何创建一个从if语句触发的二维数组?

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?

  • 写回答

2条回答 默认 最新

  • dtpwra8456 2013-10-04 09:10
    关注

    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);
        }           
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面