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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c