php csv to array with header

Solutions on MaxInterview for php csv to array with header by the best coders in the world

showing results for - "php csv to array with header"
Finn
01 Jan 2019
1function parse($file, $separ = ';')
2{
3    $arrays = array_map(function ($foo) use ($separ) {
4        return array_map("trim", str_getcsv($foo, $separ));
5    }, file($file, FILE_SKIP_EMPTY_LINES));
6
7    $header = $arrays[0];
8    unset($arrays[0]);
9
10    $array_with_keys = [];
11    foreach ($arrays as $array) {
12        $_array = [];
13        foreach ($array as $key => $value) {
14            $_array[$header[$key]] = $value;
15        }
16        $array_with_keys[] = $_array;
17    }
18
19    return $array_with_keys;
20}
Fion
21 Jan 2018
1$csv = array_map('str_getcsv', file('data.csv'));
Joe
28 May 2017
1function parse($filecsv){
2  $array = $fields = array(); $i = 0;
3  $handle = @fopen($filecsv, "r");
4  if ($handle) {
5      while (($row = fgetcsv($handle, 4096)) !== false) {
6          if (empty($fields)) {
7              $fields = $row;
8              continue;
9          }
10          foreach ($row as $k=>$value) {
11              $array[$i][$fields[$k]] = $value;
12          }
13          $i++;
14      }
15      if (!feof($handle)) {
16          return false;
17      }
18      fclose($handle);
19  }
20  return $array;
21}