good afternoon all, hope you are well 🙂

Im not actually working with csv files but I am working with strings that are layed out as csv files. I am getting the data from a mysql database.

This is an example of the data I am working with:

col1,col2,col3,paul,col5
col1,col2,z,Frank,col5
col1,col2,z,Adam,col5
col1,col2,z,Carl,col5

What I need to do is sort the column with the name alphabetically so its like this:

col1,col2,z,Adam,col5
col1,col2,z,Carl,col5
col1,col2,z,Frank,col5
col1,col2,paul,col4,col5

Any ideas how to do this?

I could use on my SQL query ORDER BY name ASC

but the problem is, the data being stored in the database is in an encrypted format.

many thanks
adam

    hmm... what puzzles me is that the record with the name "paul" has it on the 3rd field, while the other records have the name on the 4th field.

    If the names are consistently on the nth field (starting from field 0), then you can use something like:

    $count = count($array);
    
    //turn array of strings into 2 dimensional array
    for ($i = 0; $i < $count; ++$i) {
    	$array[$i] = explode(',', $array[$i]);
    }
    
    //comparison callback function
    function cmp($a, $b) {
    	static $n = 3; //the nth field
    	//use strcasecmp() for case-insensitive comparison
    	return strcmp($a[$n], $b[$n]);
    }
    
    //sort using callback function
    usort($array, 'cmp');
    
    //turn 2 dimensional array into array of strings
    for ($i = 0; $i < $count; ++$i) {
    	$array[$i] = implode(',', $array[$i]);
    }

      Many thanks for your quick reply

      that was just a typo ive corrected it now

      and you are a genius! function works amazingly 🙂

      many thanks!

        Write a Reply...