maharg
Technical User
- Mar 21, 2002
- 184
Hi I have a sort script which works fine for arrays.
A sample array...
For example to alphabetically sort array $somearray by key lastname I use...
But, I would like to use a variable so I can declare the key name once only, something like this...
But my syntax is wrong and it fails to sort. Can't find a way which works, any help much appreciated!
Thanks
Maharg.
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.