如何使用PHP将CSV解析为多维数组?

时间:2014-01-06 20:06:47

标签: php arrays csv multidimensional-array

我有一个包含以下内容的CSV文件:

Date,Transaction details,Debit,Credit
January 03 2014,POS transaction,"36,80",
,Card No: xxxx xxxx xxxx xxxx,,
,Terminal: AUCHAN ROMANIA SA  RO  CLUJ NAPOCA,,
,Date: 02-01-2014 AuthID: 382542,,
January 03 2014,POS transaction,"116,69",
,Card No: xxxx xxxx xxxx xxxx,,
,Terminal: AUCHAN ROMANIA SA  RO  CLUJ NAPOCA,,
,Date: 02-01-2014 AuthID: 374829,,
December 31 2013,Fees and taxes,"1,00",
,Monthly SMS alerts service fee: 1,,

我正在尝试创建一个这样的数组:

Array
(
    [0] => Array
        (
            [Date] => January 03 2014
            [Transaction details] => POS transaction
            [Debit] => 36,80
            [Credit] =>
            [Card No.] => Card No: xxxx xxxx xxxx 2113
            [Notes] => Terminal: AUCHAN ROMANIA SA  RO  CLUJ NAPOCA
            [Date and AuthID] => Date: 02-01-2014 AuthID: 382542
        )

    [1] => Array
        (
            [Date] => January 03 2014
            [Transaction details] => POS Transaction
            [Debit] => 116,69
            [Credit] =>
            [Card No.] => Card No: xxxx xxxx xxxx 2113
            [Notes] => Terminal: AUCHAN ROMANIA SA  RO  CLUJ NAPOCA
            [Date and AuthID] => Date: 02-01-2014 AuthID: 374829
        )

    [2] => Array
        (
            [Date] => January 03 2014
            [Transaction details] => Fees and taxes
            [Debit] => 1,00
            [Credit] =>
            [Card No.] =>
            [Notes] => Monthly SMS alerts service fee
            [Date and AuthID] =>
        )
)

我特别想保留 Notes 字段,因为我稍后会使用该字段对事务进行分类。

我感谢任何帮助。

编辑:我也想到了如何将CSV解析为数组,但我无法弄清楚如何将一行或多行合并到数组中的数组中。也许我的问题描述得不够清楚。

当然这是要返回的数组:

array(258) {
  [0]=>
  array(4) {
    ["Data"]=>
    string(16) "January 03 2014"
    ["Detalii tranzactie"]=>
    string(13) "POS transaction"
    ["Debit"]=>
    string(5) "36,80"
    ["Credit"]=>
    string(0) ""
  }
  [1]=>
  array(4) {
    ["Data"]=>
    string(0) ""
    ["Detalii tranzactie"]=>
    string(29) "Nr. card: xxxx xxxx xxxx 2113"
    ["Debit"]=>
    string(0) ""
    ["Credit"]=>
    string(0) ""
  }
  [2]=>
  array(4) {
    ["Data"]=>
    string(0) ""
    ["Detalii tranzactie"]=>
    string(44) "Terminal: AUCHAN ROMANIA SA  RO  CLUJ NAPOCA"
    ["Debit"]=>
    string(0) ""
    ["Credit"]=>
    string(0) ""
  }
}

2 个答案:

答案 0 :(得分:1)

在将数据呈现为CSV文件的php文件中,使用foreach循环遍历多维数组。

说,你的数组被称为$csv_array。然后遍历这个数组,如:

foreach($csv_array as $csv_data1)
{
  foreach($csv_data1 as $data)
  {
    echo "\"".$data."\"".",";  
  }
 echo "\n";
}

这将为多维数组正确呈现数据。

这是在csv文件中检索数据的基本思路,您可以根据尺寸对数组进行测试。

答案 1 :(得分:0)

$rows = array_map('str_getcsv', file('myfile.csv'));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
  $csv[] = array_combine($header, $row);
}