What are some best practices for efficiently reading and grouping entries from a CSV file in PHP?

When reading and grouping entries from a CSV file in PHP, it's important to efficiently process the data to avoid performance issues. One way to achieve this is by using the fgetcsv() function to read the file line by line and then grouping the entries based on a specific criteria, such as a common key. This can be done by creating an associative array where the key is the grouping criteria and the value is an array of entries that belong to that group.

// Open the CSV file for reading
$file = fopen('data.csv', 'r');

// Initialize an empty array to store grouped entries
$groupedEntries = [];

// Read the CSV file line by line
while (($data = fgetcsv($file)) !== false) {
    // Group entries based on a specific criteria, such as the first column
    $groupingKey = $data[0];
    
    // Add the entry to the corresponding group
    $groupedEntries[$groupingKey][] = $data;
}

// Close the file
fclose($file);

// Output the grouped entries for further processing
var_dump($groupedEntries);