将CSV文件读取为二维数组,以首行作为键名
Convert CSV to Associative Array in PHP
Your current code is on the right track—it reads the CSV rows into a 2D array—but to get the associative structure you want (where each data row uses the CSV headers as keys instead of numeric indices), we just need to add a few key steps.
Here's the polished implementation that will give you your desired output:
$filename = 'your_file.csv'; // Don't forget to replace this with your actual file path $twoDarray = []; if (($handle = fopen($filename, "r")) !== FALSE) { // First, grab the header row to use as keys $headers = fgetcsv($handle, 1000, ","); if ($headers) { // Make sure we actually got headers // Now loop through each data row while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // Combine headers with the row data to make an associative array // Optional: Skip rows that don't match the header count to avoid errors if (count($data) === count($headers)) { $twoDarray[] = array_combine($headers, $data); } } } fclose($handle); } // Check the result print_r($twoDarray);
Breakdown of the changes:
- Capture Headers: We read the first row separately using
fgetcsvto get our header keys (titleA,titleB,titleC). - Associate Rows with Headers: For each subsequent data row,
array_combine()pairs each header with its corresponding value from the row, creating the associative sub-arrays you need. - Guard Clause: The check for matching column counts prevents warnings if any rows have missing or extra values (you can adjust this to handle those cases differently if needed, like logging errors).
When you run this, you'll get exactly the output you specified:
Array ( [0] => Array ( [titleA] => data1A [titleB] => data1B [titleC] => data1C ) [1] => Array ( [titleA] => data2A [titleB] => data2B [titleC] => data2C ) )
This method is efficient, leverages PHP's native CSV handling, and keeps your code clean and maintainable.
内容的提问来源于stack exchange,提问作者Federico
相关产品推荐
相关产品推荐

