Sort A1,A2…Z9,Z10,AA1,AA2…AZ9,AZ10 PHP

This tutorial I would like to explain how to read the data from the csv ,sort the alphabet in order A1,A2,A3…..Z8,Z9,Z10,AA1,AA2,AA3,……….AZ1,AZ2….AZ8,AZ9,AZ10 and return the sorted data back to the csv.

Please refer the demo csv table which contains three fields
Unsorted Excel Data

  • Product_id
  • Quantity
  • Pick Location

This tutorial I am explaining how to sort the pick location in the ascending order.

Step by step explanation :

  1. Read data from the CSV
  2. Split and sort the data using usort() function
  3. Write the sorted data back to the CSV

Read data from the CSV

function readCSV() {
   $csv = array_map('str_getcsv', file('data.csv'));
   array_shift($csv);
   $csvData = splitandSort($csv);
   createCSV($csvData);
}

Using the function as a first step we read the data from the data.csv file using the str_getcsv() built function. After that use the array_shift() function to remove the header data. Then call the splitandsort() function.

Split and sort the data using usort() function

If we try the sort the above pick_location field using the natural sorting algorithm it will sort the data in natural order ie (A1 ,A2,A3…AA1,AA2…..Z1,Z10). But in case we need to sort the data in a different manner as shown above.

For that we need to split the pick location using the regular expression and create two groups and sort them separately (using usort() function). After that we need to merge the groups into one to get the final result as shown below.

function splitandSort($csv) {

    foreach($csv  as $row) {
        if (preg_match("/([A-Z]){2}/i", $row['2'])) {
            $grp2[] = $row;
        } else {
            $grp1[] = $row;
        }
    }
    usort( $grp1,  'sortData'  );
    usort( $grp2, 'sortData'  );
    $result = array_merge($grp1,$grp2);
    return $result;
}

function sortData($a, $b) {
    return strnatcmp($a['2'], $b['2']);
}

Sort array and CSV file

function createCSV($csvData) {
    
    header( 'Content-Type: application/excel' );
    header( 'Content-Disposition: attachment; filename="data.csv"' );

    $fp = fopen( 'php://output', 'w' );
    foreach ( $csvData as $row ) {
        fputcsv( $fp, $row, ',' );
    }

    fclose( $fp );
    
}

After sorting we get the data as shown below.

Sorted CSV Data

If you have any further queries please post a comment here.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*