0

This works. It's sort-of a generic csv file importer and key assigner. Looking for feedback how this approach could be made more elegant. I started learning php last week. This forum is fantastic.

<?php
$csvfilename = "sdb.csv";
$filekeys = array('SSID','EquipName','EquipTypeSignalName','elecpropID');

$records = InputCsvFile($csvfilename,$filekeys);

function InputCsvFile($filename,$filekeys){
 $array1 = array_map('str_getcsv', file($filename));
 foreach($array1 as $element){
  $int1 = 0;
  unset($array3);
  foreach($filekeys as $key){
   $array3[$key] = $element[$int1];
   $int1++;}
  $array2[] = $array3;}
 return $array2;}
?>
1
  • Wow! More CSV parsing! Today Im paste link of my CSV parser (special for big data and parse line by line). Can/will you test it? Commented Jan 9, 2016 at 1:28

1 Answer 1

3

Using array_map() is clever, but since you have to further process each row, is somewhat unnecessary. I would rewrite InputCsvFile like this:

function InputCsvFile($filename, array $columns) {
    $expectedCols = count($columns);
    $arr = [];

    // NOTE: Confirm the file actually exists before getting its contents
    $rows = file($filename);

    foreach($rows as $row) {
        $row = str_getcsv($row);

        if (count($row) == $expectedCols)) {
            $arr[] = array_combine($filekeys, $element);
        } else {
            // Handle the column count mismatch. The test is required because
            // otherwise, array_combine will complain loudly.
        }
    }

    return $arr;
}

Alternatively, since you're dealing with files, you could loop on fgetcsv(), rather than using file() + str_getcsv(). Using fgetcsv() will use less memory (since the entire file doesn't have to be read in entirely and be kept in memory through the duration of the iteration), which may or may not be a concern depending on your file sizes.

array_combine() (which incidentally, is one of my favorite functions in PHP) creates a new array given arrays of keys (your list of columns in your $filekeys array) and values (the processed rows from the csv), and is practically tailor-made for turning csv files into more usable arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

Good points. Thanks. Yes your approach worked, after some editing. I'm glad you showed me how to do it with array_combine. I tried to get array_combine to work, but array_map constructs an array that array_combine doesn't like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.