0

I have an array that I would like to sort based on its values. However, because values can be equivalent, I need to be able to access the keys in the sort function's callback as well in order to figure out the correct ordering. I am currently using uasort in order to sort by value, while maintaining key association, but cannot figure out how to access the keys from the callback comparison function.

Example array:

Array(
    [a1] => date1,
    [a2] => date2,
    [a3] => date1
)

I need to sort by the dates, but since a1 and a3 are the same date, I need to check whether it's a1 or a3.

0

1 Answer 1

2

My understanding is that you want to sort by value, then by key. To do this you can use array_multisort() and pass first your values then your keys:

$k = array_keys($array);
$v = array_values($array);

array_multisort($array, SORT_ASC, $v, SORT_ASC, $k);

Example output (after print_r($array)):

Array
(
    [a1] => date1
    [a3] => date1
    [a2] => date2
)
Sign up to request clarification or add additional context in comments.

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.