Sorting Multidimensional Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
litebearer
Forum Contributor
Posts: 194
Joined: Sat Mar 27, 2004 5:54 am

Sorting Multidimensional Array

Post by litebearer »

Pimptastic | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


The scenario:

1. flatfile database
       consists of records delimited by carriage returns.
       records have fields delimited by commas

      example of file structure and content:

Code: Select all

1,Nicholas,,Stoia,6992 Biscayne,White Lake,MI,48383,1,13,1946,,,,,,,
         2,Myles,Edward,Dean,,,WV,,0,0,0,,,,,,,
         3,Sharon,Marie,Stoia,6992 Biscayne,White Lake,MI,48383,7,16,1955,,,,,,,
         4,Jonathon,Hunter,Stoia,6992 Biscayne,White Lake,MI,48383,12,13,1988,,,,,,,
         5,Rebecca,,Dean,,,WV,,0,0,0,,,,,,,
         6,Gilbert,Rial,Stebbins,22600 Bluewater Drive,Macomb Twp,MI,48044,0,0,0,,,,,,,
         7,Beverly,,Stebbins,22600 Bluewater Drive,Macomb Twp,MI,48044,0,0,0,,,,,,,
         8,Sean,Michael,Dean,167 Weston Road,Wellesley,MA,02482,0,0,0,,,,,,,
2. multidimensional array created as follows:

Code: Select all

// read file into array
        $file = file("faf.txt");
        $count = count($file);

        // convert first array to multidimensional array
        $i = 0;
        for($i=0;$i<$count;$i++) {
	         $file_cards[$i] = explode(",", $file[$i]);
        }
3. sort by last name (

Code: Select all

function compare($x, $y){
          if ( $x[3] == $y[3] )
             return 0;
          else if ( $x[3] < $y[3] )
             return -1;
          else
             return 1;
        }

        usort($file_cards, 'compare');

The Question:

The above works fine; however,
in addition to sorting by last name

Code: Select all

$file_cards[x][3]
I would like to further sort by first name

Code: Select all

$file_cards[x][1]
and then by middle name

Code: Select all

$file_cards[x][2]
.


How?

Thanks,

Lite...


Pimptastic | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Post Reply