Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variables in sorting arrays 1

Status
Not open for further replies.

maharg

Technical User
Mar 21, 2002
184
Hi I have a sort script which works fine for arrays.

A sample array...

Code:
$somearray = array
(
"applicant1"=>array(
"firstname" => "Graham",  
"lastname" => "Laming",  
"sex" => "male", 
 "age" => "50" 
 ),
 
 "applicant2"=>array(
"firstname" => "Hanna",  
"lastname" => "Laming",  
"sex" => "female", 
 "age" => "17" 
 ),
 
 "applicant3"=>array(
"firstname" => "Bert",  
"lastname" => "Acrodong",  
"sex" => "male", 
 "age" => "42" 
 ),
 
 "applicant4"=>array(
"firstname" => "Emily",  
"lastname" => "Makaraka",  
"sex" => "female", 
 "age" => "23" 
 )
 
 
 );



For example to alphabetically sort array $somearray by key lastname I use...

Code:
function compare_field($a, $b) { return strnatcmp($a['lastname], $b['lastname']); } 
// sort alphabetically by lastname 
usort($somearray, 'compare_field');


But, I would like to use a variable so I can declare the key name once only, something like this...


Code:
$field_to_sort = "'lastname'";
function compare_field($a, $b) { return strnatcmp($a[$field_to_sort], $b[$field_to_sort]); } 
// sort alphabetically by lastname 
usort($somearray, 'compare_field');

But my syntax is wrong and it fails to sort. Can't find a way which works, any help much appreciated!

Thanks

Maharg.
 
Hi

See Variable scope.
PHP:
[b]function[/b] [COLOR=darkgoldenrod]compare_field[/color][teal]([/teal][navy]$a[/navy][teal],[/teal] [navy]$b[/navy][teal])[/teal] [teal]{[/teal] [highlight][b]global[/b] [navy]$field_to_sort[/navy][teal];[/teal][/highlight] [b]return[/b] [COLOR=darkgoldenrod]strnatcmp[/color][teal]([/teal][navy]$a[/navy][teal][[/teal][navy]$field_to_sort[/navy][teal]],[/teal] [navy]$b[/navy][teal][[/teal][navy]$field_to_sort[/navy][teal]]);[/teal] [teal]}[/teal]


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top