...

View Full Version : Sorting Multidimensional array



litebearer
08-03-2006, 03:25 AM
The scenario:

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

example of file structure and content:


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:



// 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 (

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
$file_cards[x][3]
I would like to further sort by first name
$file_cards[x][1]
and then by middle name
$file_cards[x][2] .


How?

Thanks,

Lite...

Fumigator
08-03-2006, 04:36 PM
The only way I've found to do this is first sort by the middle name first, then append a sequential number onto the middle name, then sort by the first name+middle name, append a sequential number onto that as well, then sort by a compound value of all three sortkeys-- "lastname.firstname.middlename". So the following:

Nielson, Olivia Sue
Smith, Mike John
Smith, Mike Doug
Nielson, Tom Duke
Smith, Mike Melvin
Smith, Pete Bernard
Nielson, Tom Applehead
Smith, Adam Paul

Would first look like

Nielson, Tom Applehead100000
Smith, Pete Bernard100001
Smith, Mike Doug100002
Nielson, Tom Duke100003
Smith, Mike John100004
Smith, Mike Melvin100005
Smith, Adam Paul100006
Nielson, Olivia Sue100007

And then like

Smith, Adam100000 Paul100006
Smith, Mike100001 Doug100002
Smith, Mike100002 John100004
Smith, Mike100003 Melvin100005
Nielson, Olivia100004 Sue100007
Smith, Pete100005 Bernard100001
Nielson, Tom100006 Applehead100000
Nielson, Tom100007 Duke100003


And finally like

Nielson, Olivia100004 Sue100007
Nielson, Tom100006 Applehead100000
Nielson, Tom100007 Duke100003
Smith, Adam100000 Paul100006
Smith, Mike100001 Doug100002
Smith, Mike100002 John100004
Smith, Mike100003 Melvin100005
Smith, Pete100005 Bernard100001

The algorithm I've used in the past uses a temporary variable that I do all that appending with so I don't have to strip it all off later. I can dig it out if you want to see it.

litebearer
08-04-2006, 12:25 AM
Thanks. I'll give it a try.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum