Answers for "php csv to array with headers"

PHP
1

php csv to array with header

function parse($file, $separ = ';')
{
    $arrays = array_map(function ($foo) use ($separ) {
        return array_map("trim", str_getcsv($foo, $separ));
    }, file($file, FILE_SKIP_EMPTY_LINES));

    $header = $arrays[0];
    unset($arrays[0]);

    $array_with_keys = [];
    foreach ($arrays as $array) {
        $_array = [];
        foreach ($array as $key => $value) {
            $_array[$header[$key]] = $value;
        }
        $array_with_keys[] = $_array;
    }

    return $array_with_keys;
}
Posted by: Guest on May-19-2021
-1

php csv to array with headers

function parse($filecsv){
  $array = $fields = array(); $i = 0;
  $handle = @fopen($filecsv, "r");
  if ($handle) {
      while (($row = fgetcsv($handle, 4096)) !== false) {
          if (empty($fields)) {
              $fields = $row;
              continue;
          }
          foreach ($row as $k=>$value) {
              $array[$i][$fields[$k]] = $value;
          }
          $i++;
      }
      if (!feof($handle)) {
          return false;
      }
      fclose($handle);
  }
  return $array;
}
Posted by: Guest on March-31-2021

Browse Popular Code Answers by Language