Jump to content


Photo

Sorting multidimensional array by multiple fields


  • Please log in to reply
2 replies to this topic

#1 litebearer

litebearer
  • Members
  • PipPipPip
  • Advanced Member
  • 2,357 posts
  • Locationwhite lake michigan

Posted 02 August 2006 - 02:40 PM

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...



all the brothers were valiant!

[br][br]The truely intelligent people are not those who create the dots; rather they are they ones with the ability to connect the dots into a coherent picture

#2 hitman6003

hitman6003
  • Members
  • PipPipPip
  • Advanced Member
  • 1,807 posts

Posted 03 August 2006 - 01:52 AM

Well, one way would be to format the key as the full name:

$file = file("faf.txt");

foreach ($file as $line) {
	$line = explode(",", $line);
	$name = $line[0] . ", " . $line[1] . ", " . $line[2];
	$data[$name] = $line;
}

ksort($data);


#3 hitman6003

hitman6003
  • Members
  • PipPipPip
  • Advanced Member
  • 1,807 posts

Posted 03 August 2006 - 01:53 AM

Another option would be array_multisort (http://www.php.net/array_multisort)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users