Jump to content

PHP Coding Question arrays usort


joelhop

Recommended Posts

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;
else
return 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;
else
return 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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.