dongliang7545 2016-09-20 22:51
浏览 96
已采纳

在PHP中使用while()合并数组

I found the need to use element keys as identifiers and therefore stumbled upon the following predicament.

I am reading a file and parsing it in order to extract the filenames and then work with them. As I am looping through all the lines in the file, I am creating a new array for every match to the regular expression:

$file = fopen('/home/user/log.txt', 'r');

if ($file) {
  while (($line = fgets($file)) !== false) {
     if (preg_match('~^/[^:]+~m', $line, $files)) { //match everything until the first ':' to get file names
         var_dump($files);
     }
  }
}

Thus, I get:

array (size=1)
  0 => string '/home/user/whatever.php' (length=23)
array (size=1)
  0 => string '/home/user/run.php' (length=18)
array (size=1)
  0 => string '/home/user/sth.php' (length=18)

I would like to merge them all into one single array so that they may have different keys. Can that be achieved in this scenario or should I consired rewriting the loops?

  • 写回答

1条回答 默认 最新

  • duanmei1694 2016-09-20 22:58
    关注

    Do something like this instead to add them to an array as you loop:

    $file = fopen('/home/user/log.txt', 'r');
    $array = [];
    
    if ($file) {
      while (($line = fgets($file)) !== false) 
      {
         if (preg_match('~^/[^:]+~m', $line, $files)) 
         { //match everything until the first ':' to get file names
             array_push($array, $files);
         }
      }
    }
    
    var_dump($array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用