Jump to content

Archived

This topic is now archived and is closed to further replies.

joelhop

PHP Coding Question arrays usort

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 ???

Share this post


Link to post
Share on other sites
[code]
function ascORDER($x, $y)
{
global $z;

if ( $x[$z] == $y[$z] )
return 0;
else if ( $x[$z] < $y[$z] )
return -1;
else
return 1;
}[/code]

then

$z = 1;
usort(....);

Share this post


Link to post
Share on other sites

×

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.