user3781236
user3781236

Reputation: 728

How to sort array by value, with access to key in callback function?

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.

Upvotes: 0

Views: 264

Answers (1)

scrowler
scrowler

Reputation: 24405

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
)

Upvotes: 2

Related Questions