0

I'm having the following csv file

$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"
]

What I want to do is to display the content of the csv file into a html-table, but first I want to convert this to an associative array. How can I do this? Does PHP provide a build-in function for this?

1

1 Answer 1

0

The usual way to do this is with 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));

Result:

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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.