joelhop Posted July 21, 2006 Share Posted July 21, 2006 I am using the php usort()command to sort an array.Example Array:$sdArray = array( array( 'Fred', 'Chode', 31 ),array( 'Shaggy', 'Hippie', 23 ),array( 'Scooby', 'Dog', 7));Example ascORDER() function:function ascORDER($x, $y){if ( $x[0] == $y[0] )return 0;else if ( $x[0] < $y[0] )return -1;elsereturn 1;}Example usort:usort($sdArray, 'ascORDER');This works all fine and good, resorts the array by key position 0, or the name (Fred, Shaggy, Scooby). However if I want to change what I want to sort by, I have to go into ascORDER() and change the 0 to 1 or a 2 to change which key I want to sort by. This also works, but what I would like to do is rewrite the ascORDER() function to replace the hard coded key position to a variable as such:function ascORDER($x, $y){if ( $x[$z] == $y[$z] )return 0;else if ( $x[$z] < $y[$z] )return -1;elsereturn 1;}Where $z is the key position. Then I would simply like to pass with value of $z with:usort($sdArray, 'ascORDER'); + ($z)Obviously that isn't the solution, but does anyone have any idea how you can pass a variable to the user-defined comparison function (in this case ascORDER) when using usort?Thanks!-Karl ??? Link to comment https://forums.phpfreaks.com/topic/15290-php-coding-question-arrays-usort/ Share on other sites More sharing options...
Barand Posted July 21, 2006 Share Posted July 21, 2006 [code]function ascORDER($x, $y){global $z;if ( $x[$z] == $y[$z] )return 0;else if ( $x[$z] < $y[$z] )return -1;elsereturn 1;}[/code]then$z = 1;usort(....); Link to comment https://forums.phpfreaks.com/topic/15290-php-coding-question-arrays-usort/#findComment-61890 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.