duanan5940 2013-12-11 16:03
浏览 8
已采纳

通过空格插入数组

I have this TXT file, which each line I would to insert into array, like this:

Array ( [0] => [1] => 8100 [2] => 623 [3] => 09:04 [4] => AM [5] => 00:26 [6] => L [7] => S-ED [8] => 768 [9] => #4506856439 [10] => 00:01 [11] => )

 CO     USER    TIME    DURATION  TYPE   ACCOUNT_CODE  CALLED_NUM      RING_TIME
 8100   623   09:04 AM     00:26  L S-E               250821613987
 8021   8816  09:06 AM     00:20  I S-E  D 768        #4506856439        00:01
 8020         09:06 AM            I  N   D 603        #45424044499        00:30
 8011         09:07 AM     00:11  I S-E  D 727        #7546355292        00:02
  "     8817               00:11  
  "                        00:02  H  
 8100   623   09:07 AM     00:01  L S-E               5542204034
 8007   8818  09:08 AM     00:13  I S-E  D 618        #45269021726        00:01
 8013   8811  09:09 AM     00:01  I S-E  D 770        #436217227         00:01
 8014         09:10 AM     00:16  I S-E  D 652        #4523859922        00:01

I'd like to insert it into an array with all parameters, even if empty,
but I can't get it work.

I tried this:

$fh = fopen('captures/131210.txt','r');
 while ($line = fgets($fh)) {
  $tempexp = preg_split('/\s+/', $line);
  print_r($tempexp);
  echo "<br />";
 }
fclose($fh)

But it gives out weird outputs for some values, like this:

Array ( [0] => [1] => " [2] => 8812 [3] => 00:16 [4] => )

Help would be much appreciated!

  • 写回答

1条回答 默认 最新

  • dounai6626 2013-12-11 16:11
    关注

    If the layout of your text file is purely based on spaces you can used the exact columns to extract the data. Since the columns are not of equal width you cannot simply write it in one loop.

    Use the substr function to get part of the line (first number is index, second number is length to read)

    $fh = fopen('captures/131210.txt','r');
     while ($line = fgets($fh)) {
      $co = substr($line, 0, 7);
      $user = substr($line, 7, 6);
      ... etc ...
      echo "<br />";
     }
    fclose($fh)
    

    You might need to parse the separate parts further down dependent on the content and what you want to do with it - parse as integer, date, time etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码