1

Is there any way to "custom" sort an array? For instance, if I have the following numbers:

$array = array('0' => 1, '1' => 2, '2' => 3);

I would like it to order them in this fashion:

$array = array('0' => 2, '1' => 1, '2' => 3);

How would I do this or is it not possible? I am basically wanting to list this array in one database field for each user, but each order will be different depending on how the user sorts the array.

1
  • What's the ordering logic? What determines whether a value is pushed forward or backward? Commented Aug 20, 2010 at 23:01

3 Answers 3

4

You can use

  • usortSort an array by values using a user-defined comparison function or
  • uksortSort an array by keys using a user-defined comparison function or
  • uasortSort an array with a user-defined comparison function and maintain index association

Each of these accepts an array and a user-defined comparison function aka callback. What you put into the comparion function is up to you. As of PHP5.3 you can also use SplHeaps to create ordered collections.

Sign up to request clarification or add additional context in comments.

Comments

0

you may also want to have a look at array_multisort()

Comments

0

It might be better to let the database sort the array upon retrieval with the users settings. I think that is almost always preferable over sorting in PHP.

edit: I forgot that the array is probably stored as a single object so the database just handles it as an object and not an array. To still enable serverside (database server) sorting, arrays could also be expressed as seperate tables:

userID : index0 userID : index1 etc...

but this might give too much data overhead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.