将csv行转换为关联数组

时间:2018-02-10 17:59:32

标签: php csv associative-array

我有以下csv文件

$file = file_get_contents($url);

// file
Date,Value1,Value2
17-Nov-17,34,42
16-Nov-17,22,35
15-Nov-17,19,24

$csv = explode("\n", $file);

// dump
array:10 [▼
  0 => "Date,Value1,Value2
  1 => "17-Nov-17,34,42"
  2 => "16-Nov-17,22,35"
  3 => "15-Nov-17,19,24"
]

我想要做的是将csv文件的内容显示到html表中,但首先我要将其转换为关联数组。我怎样才能做到这一点? PHP是否为此提供了内置函数?

1 个答案:

答案 0 :(得分:0)

通常的方法是使用array_combine

$file = file_get_contents($url);    // Read file into array
$rows = explode("\n", $file);       // Separate lines
$headings = explode(',', $rows[0]); // Turn headings on first line into array
unset($rows[0]);                    // Remove headings from data set
$data = [];
foreach ($rows AS $row)
    $data[] = array_combine($headings, explode(',', $row));

结果:

array(3) {
  [0]=>
  array(3) {
    ["Date"]=>
    string(9) "17-Nov-17"
    ["Value1"]=>
    string(2) "34"
    ["Value2"]=>
    string(2) "42"
  }
  [1]=>
  array(3) {
    ["Date"]=>
    string(9) "16-Nov-17"
    ["Value1"]=>
    string(2) "22"
    ["Value2"]=>
    string(2) "35"
  }
  [2]=>
  array(3) {
    ["Date"]=>
    string(9) "15-Nov-17"
    ["Value1"]=>
    string(2) "19"
    ["Value2"]=>
    string(2) "24"
  }
}