Jump to content


Photo

PHP Coding Question arrays usort


  • Please log in to reply
1 reply to this topic

#1 joelhop

joelhop
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 21 July 2006 - 08:22 PM

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

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,020 posts

Posted 21 July 2006 - 11:16 PM

function ascORDER($x, $y)
{
global $z;

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

then

$z = 1;
usort(....);
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users