Solved

# Sort multi-dim array

Posted on 2003-03-18
Medium Priority
218 Views
I have a multi-dimensional array of the following type:

\$main['fname'][1] = "Bob"
\$main['lname'][1] = "Dole"
\$main['fname'][2] = "Bill"
\$main['lname'][2] = "Clinton"
\$main['fname'][3] = "George"
\$main['lname'][3] = "Bush"

I'd like to sort the array values alphabetically by last name ('lname') such that the return values will be:

\$main['fname'][1] = "George"
\$main['lname'][1] = "Bush"
\$main['fname'][2] = "Bill"
\$main['lname'][2] = "Clinton"
\$main['fname'][3] = "Bob"
\$main['lname'][3] = "Dole"

Can anyone suggest a way to do this?

0
Question by:shaungallagher
• 2

LVL 1

Expert Comment

ID: 8161020
hi...  PHP's array_multisort should help

ex:

array_multisort (\$main["lname"], SORT_STRING, SORT_DESC, \$main["fname"]);

Note: If you have more columns, list them at the end.
0

Author Comment

ID: 8161206
Yikes!  I forgot to mention that I'm only able to use PHP3, not PHP4, so array_multisort won't work for me.  Is there any PHP3 equivalent?
0

LVL 1

Expert Comment

ID: 8161338
Oh, bummer... I can't think of any right off, but I'll ask around
0

LVL 9

Accepted Solution

waygood earned 315 total points
ID: 8161353
You could always write your own bubble sort.

for(\$x=0;\$x<sizeof(\$main);\$x++)
{
for(\$y=x;\$y<sizeof(\$main);\$y++)
{
if(\$main['lname'][\$y]<\$main['lname'][\$y+1])
{
\$temp=\$main['lname'][\$y];
\$main['lname'][\$y]=\$main['lname'][\$y+1];
\$main['lname'][\$y+1]=\$temp;

\$temp=\$main['sname'][\$y];
\$main['sname'][\$y]=\$main['sname'][\$y+1];
\$main['sname'][\$y+1]=\$temp;

}
}
}

BUT if you defined your variables differently it would be easier. EG

\$main[1]['fname']="esef";
\$main[1]['lname']="sd";

the middle bit would just be :-

\$temp=\$main[\$y];
\$main[\$y]=\$main[\$y+1];
\$main[\$y+1]=\$temp;

0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
###### Suggested Courses
Course of the Month8 days, 5 hours left to enroll