3

I know about fgetcsv, but it doesn't really do what I'm looking for.

I have the following csv file:

productId,productName,productActive
1,test product,1
2,test product2,0

I'm looking for something that will create an array that looks like this:

array (0)
    ['productId'] => 1
    ['productName'] => test product
    ['productActive'] => 1

array (1)
    ['productId'] => 2
    ['productName'] => test product2
    ['productActive'] => 0

any ideas?

1
  • 1
    fgetcsv will serve you well in this situation. Read the first line, gather field names, then read the remaining lines and collect them into the array using the field names as keys. Commented Nov 21, 2011 at 18:26

3 Answers 3

7
// open the file.
if (($handle = fopen("in.csv", "r")) !== FALSE) {
        // read the column headers in an array.
        $head = fgetcsv($handle, 1000, ",");

        // read the actual data.
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

                // create a new array with the elements in $head as keys
                // and elements in array $data as values.
                $combined = array_combine($head,$data);

                // print.
                var_dump($combined);
        }
        // done using the file..close it,
        fclose($handle);
}

See it

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

Comments

0

Try something like this:

$rows = array();
$headers = fgetcsv($file);
while($line = fgetcsv($file)) {
    $row = array();
    foreach($line as $key => $value) {
        $row[$headers[$key]] = $value;
    }
    $rows[] = $row;
}

Comments

0

You would have to write your own function for that. It has all sorts of implicit requirements such as the first line being the key indices. If that's what you always want then you can do:

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $row_headers = fgetcsv($handle);
    $output = array();

    //don't specify a limit to the line length (i.e. 1000). 
    //just grab the whole line
    while (($data = fgetcsv($handle)) !== FALSE) {
        $num = count($data);
        $row++;
        $row_array = array();
        //For each column, create a row array with the index being
        //the column heading and the data being the row data.
        for ($c=0; $c < $num; $c++) {
            $row_array[$row_headers[$c]] = $data[$c];
        }

        //Add each row to the output
        $output[] = $row_array;
    }
    print_r($output);
}

Giving the result of:

Array ( [0] => Array ( [productId] => 1 [productName] => test product [productActive] => 1 ) [1] => Array ( [productId] => 2 [productName] => test product2 [productActive] => 0 ) )

Comments

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.