将CI上的CSV读取到阵列多维度

时间:2015-11-29 02:32:19

标签: php codeigniter csv

有一天晚上我一直在努力阅读csv并将它们放入CI的数组中。 csv看起来像这样:

<CfgGroup><DBID value="109" /><tenantDBID value="1" /><name value="group1" /><contractDBID value="0" /></CfgGroup>
<CfgGroup><DBID value="110" /><tenantDBID value="1" /><name value="group2" /><contractDBID value="0" /></CfgGroup>

基于this link,我用它来读取这个csv。但是,结果不适合我的期望, 结果是:

 NO,EIR IN,CONT,TYPE,INDEPO,JAM,KODE VSL,VESSEL,VOY,CONSIG,COND IN,CLEAN,TARE,GROSS,KAPASITAS,EX CARGO,LAST AIR),LAST HIDRO,MANU,BUILDER,OWNER
  1,1545053   ,EOLU 1111111,XXXX,21-11-2015,13:00,ABO,ALBERT OLDENDORFF   ,N001   ,ASTABUMI CIPTA      ,DMG,DIRTY,  2400, 20000,  5000,FOOD                ,  -  -    ,  -  -    ,10-11  ,                    ,APL                 
  2,1545052   ,EOLU 1234567,IM04,21-11-2015,10:00,202,WAN HAI 202         ,N 001  ,ANUGERAH AGUNG LUMIN,AVL,DIRTY,  2400, 20000,  1000,MAKANAN             ,  -  -    ,  -  -    ,11-13  ,                    ,APL                 

它很奇怪,因为标题跟随作为数组的项目。如何将它们变成这样的数组:

Array
(
[0] => Array
    (
        [] =>  NO,EIR IN,CONT,TYPE,INDEPO,JAM,KODE VSL,VESSEL,VOY,CONSIG,COND IN,CLEAN,TARE,GROSS,KAPASITAS,EX CARGO,LAST AIR),LAST HIDRO,MANU,BUILDER,OWNER
    )

[1] => Array
    (
        [] =>     1,1545053   ,EOLU 1111111,XXXX,21-11-2015,13:00,ABO,ALBERT OLDENDORFF   ,N001   ,ASTABUMI CIPTA      ,DMG,DIRTY,  2400, 20000,  5000,FOOD                ,  -  -    ,  -  -    ,10-11  ,                    ,APL                 
    )

[2] => Array
    (
        [] =>     2,1545052   ,EOLU 1234567,IM04,21-11-2015,10:00,202,WAN HAI 202         ,N 001  ,ANUGERAH AGUNG LUMIN,AVL,DIRTY,  2400, 20000,  1000,MAKANAN             ,  -  -    ,  -  -    ,11-13  ,                    ,APL                 
    )

 )

1 个答案:

答案 0 :(得分:0)

这里有与你的csv一起使用的代码,你可以把它放在帮助器里。

<?php

    $file = file("./csv.csv");
    $column_names = array_map("trim", explode(",", $file[0]));
    $data = array();

    for($i = 1; $i < count($file); $i++)
    {
        $line = $file[$i];
        $column_values = array_map("trim", explode(",", $line));
        $data[ $i ] = array_combine($column_names, $column_values);
    }

    var_dump($data);