dougan7657 2015-09-23 22:25
浏览 21
已采纳

如何将文件转换为关联数组? 并使用前3个字符作为键

I have a file like below, which I need to convert into an array:

ABCLine, Number, One
DEFNumber, Two, Line
GHIThree, Line, Number

I can get each line and turn it into a value of an array, but what I need to do is take the first 3 characters and turn that into a key and then the rest of the line into the value.

So my expected array would be:

Keys  |      Values
----------------------------
ABC   |  Line, Number, One
DEF   |  Number, Two, Line
GHI   |  Three, Line, Number

I honestly am not too sure where to begin, I've been looking all over and haven't been able to find a way to just take those first 3 characters and turn those into a key for the remainder of the line.

I started with some code, which looks like this:

<?php

  echo "Name<br/>";

  $file = "hw3.txt";
  $f1 = fopen($file, 'r');
  $array = array();


?>
  • 写回答

2条回答 默认 最新

  • duannaxin9975 2015-09-23 22:34
    关注

    This should work for you:

    Get your file into an array with file(). Then walk through your array with array_walk() and take the first 3 characters of each value and add it to the $keys array. After that you can remove the first 3 characters from the value.

    At the end just array_combine() your $keys array with $arr, e.g.

    <?php
    
    
        $arr = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $keys = [];
        array_walk($arr, function(&$v, $k)use(&$keys){
           $keys[] = substr($v, 0, 3);
           $v = substr($v, 3);
        });     
    
        $arr = array_combine($keys, $arr);
    
        print_r($arr);
    
    ?>
    

    output:

    Array
    (
        [ABC] => Line, Number, One
        [DEF] => Number, Two, Line
        [GHI] => Three, Line, Number
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘