PHP从php文件中读取行并按顺序对它们进行分组

你好,我有一个 txt 文件,其中包含如下数据:

  • ABC

  • DEF

  • ABC

  • DEF

  • 做记录

  • ABC

  • DEF

  • 做记录

我所做的是逐行读取文件并生成一个包含所有行的大数组

  array(7) {


      [0]=>

      string(3) "ABC"

      [1]=>

      string(3) "DEF"

      [2]=>

      string(3) "ABC"

      [3]=>

      string(3) "DEF"

      [4]=>

      string(3) "GHI"

      [5]=>

      string(3) "ABC"

      [6]=>

      string(3) "DEF"

      [7]=>

      string(3) "GHI"

      

      .... big array not only this 7 index 


    }

我需要的是生成一个子数组,其中包含数据 ABC、DEF 和 GHI

因此,在这种情况下,该数组必须仅包含索引 2,3,4,5,6,7,因为索引 2 以 ABC 开头,但我们需要顺序 ABC DEF 和 GHI。我希望我的解释很清楚,换句话说,我需要每 3 个索引检查一次这个大数组,如果索引 0 = ABC

  • 索引 1 = DEF

  • 索引 2 = GHI 推入空数组

  • 索引 3 = ABC

  • 索引 4 = DEF

  • 索引 5 = GHI 推入空数组

  • 索引 6 = ABC // 删除它

  • 索引 7 = DEF // 删除它

  • 索引 8 = ABC

  • 索引 9 = DEF

  • 指数 10 = GHI

将 8,9,10 推入空数组

排除..

我真的希望我能用好话解释,以便您能够理解并尝试帮助我

谢谢


Smart猫小萌
浏览 69回答 1
1回答

慕盖茨4494581

解决方案1:在for循环中迭代数组,如果当前元素是ABC,DEF则下一个是,GHI然后将其添加到结果中。<?php$input = [&nbsp; 'ABC', //&nbsp; 'DEF', //&nbsp; 'GHI', //&nbsp; 'ABC',&nbsp; 'DEF',&nbsp; 'ABC', //&nbsp; 'DEF', //&nbsp; 'GHI', //&nbsp; 'ABC',&nbsp; 'GHI',&nbsp; 'DEF',];// 1$result = [];for($i=0;$i<count($input)-2;$i++) {&nbsp; if ($input[$i] === 'ABC' && $input[$i+1] === 'DEF' && $input[$i+2] === 'GHI') {&nbsp; &nbsp; $result[] = $input[$i];&nbsp; &nbsp; $result[] = $input[$i+1];&nbsp; &nbsp; $result[] = $input[$i+2];&nbsp; }}var_dump($result);ABCDEFGHI解决方案 2 是一个额外的好处 - 不同的方法:将此数组加载到一个长字符串中,搜索在该字符串中可以找到多少次。多次重复此字符串并将其以 3 个字符块的形式加载回数组:// 2$result = str_split(str_repeat('ABCDEFGHI', substr_count(implode('', $input), 'ABCDEFGHI')), 3);var_dump($result);输出:array(6) {&nbsp; [0]=>&nbsp; string(3) "ABC"&nbsp; [1]=>&nbsp; string(3) "DEF"&nbsp; [2]=>&nbsp; string(3) "GHI"&nbsp; [3]=>&nbsp; string(3) "ABC"&nbsp; [4]=>&nbsp; string(3) "DEF"&nbsp; [5]=>&nbsp; string(3) "GHI"}array(6) {&nbsp; [0]=>&nbsp; string(3) "ABC"&nbsp; [1]=>&nbsp; string(3) "DEF"&nbsp; [2]=>&nbsp; string(3) "GHI"&nbsp; [3]=>&nbsp; string(3) "ABC"&nbsp; [4]=>&nbsp; string(3) "DEF"&nbsp; [5]=>&nbsp; string(3) "GHI"}
打开App,查看更多内容
随时随地看视频慕课网APP