doudiyu1639 2014-06-30 09:59
浏览 28
已采纳

PHP数组包含字符串

i create a method that will read a file with the application/octet type and here are some of the code. Raw data :

GTHHS;MEKID Interface;5496;2012-07-20; NM1;081;IN1;980898989;2001-01-15;Mr;Gaf;Uhkil;Uhkil,Gaf;PRI;Gaf

 $contents = file_get_contents($tmp_filename);
 $stringContents = explode(";", $contents); 

Now it gives me this output :

Array
(
    [0] => GTHHS
    [1] => MEKID Interface
    [2] => 5496
    [3] => 2012-07-20
NM1
    [4] => 081
    [5] => IN1
    [6] => 980898989
    [7] => 2001-01-15
    [8] => Mr
    [9] => Gaf
    [10] => Uhkil
    [11] => Uhkil,Gaf
    [12] => PRI
    [13] => Gaf
PR1
    [14] => 081
    [15] => IN1
    [16] => 20730089
    [17] => 7 The Schooner
    [18] => Auhaas
    [19] => Huuula Ave
    [20] =>  
    [21] => Kishma
PR2
    [22] => 081
    [23] => IN1
    [24] => 232323233
    [25] => 400006
    [26] => HGD
    [27] => M
    [28] => M
    [29] => 2007-10-16
    [30] => 1976-03-31
);

How can i make the NM1, PR1 as the head of array like this :

Array (
     [NM1] = array(
            [0] => GTHHS 
            [1] => MEKID Interface 
            [2] => 5496 
            [3] => 2012-07-20
            )
);

I am planning also to make the inner array [0]-[3] as json.

  • 写回答

1条回答 默认 最新

  • dtwr2012 2014-06-30 10:59
    关注

    If you explode the contents by you have each line starting with that identifier. If you then just explode by ; in that line and add it as a sub array, you got it like you want.

    This actually looks like a plain old CSV file with your ifentifier in line one. If so, try something like this:

    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, ";", "\"", "
    ")) !== FALSE)
        {
            $key = array_shift($row);
            $data[$key] = $row;
        }
        fclose($handle);
    }
    
    echo json_encode($data);
    

    http://php.net/manual/en/function.str-getcsv.php

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?