PHP array multiple sort - by value then by key?
As Scott Saunders hints in his comment to David's solution, you can use the array_keys() and array_values() functions to get rid of the loop. In fact, you can solve this in one line of code:
array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
The previous proposed solution seems logical, but it just doens't work:
ksort($arrTags);
arsort($arrTags);
The complete PHP code to realize the asked sorting, will be:
$k = array_keys($arrTags);
$v = array_values($arrTags);
array_multisort($k, SORT_ASC, $v, SORT_DESC);
$arrTags = array_combine($k, $v);
Please note that array_multisort() uses references on user input, so you'll have to use two temporary variabels ($k and $v) to supply content as user input. This way array_multisort() can change the content. Later on, rebuild the sorted array via array_combine().
I've built a reusable function to accomplish this task:
<?php
/**
* Sort a multi-dimensional array by key, then by value.
*
* @param array Array to be sorted
* @param int One of the available sort options: SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING
* @param int One of the available sort options: SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING
* @return void
* @example The following array will be reordered:
* $a = array(
* 'd' => 4,
* 'c' => 2,
* 'a' => 3,
* 'b' => 1,
* 'e' => 2,
* 'g' => 2,
* 'f' => 2,
* );
* SortArrayByKeyThanValue($a); # reorder array to: array(
* 'b' => 1,
* 'c' => 2,
* 'e' => 2,
* 'f' => 2,
* 'g' => 2,
* 'a' => 3,
* 'd' => 4,
* );
* @author Sijmen Ruwhof <sijmen(a)secundity.com>
* @copyright 2011, Secundity
*/
function SortArrayByKeyThanValue (&$pArray, $pSortMethodForKey = SORT_ASC, $pSortMethodForValue = SORT_ASC)
{
# check user input: sorting is not necessary
if (count($pArray) < 2)
return;
# define $k and $v as array_multisort() needs real variables, as user input is put by reference
$k = array_keys ($pArray);
$v = array_values($pArray);
array_multisort(
$v, $pSortMethodForValue,
$k, $pSortMethodForKey
);
$pArray = array_combine($k, $v);
}
?>
Have a look at examples #3: http://php.net/manual/en/function.array-multisort.php
You'll need to create two arrays to use as indexes; one made up of the original array's keys and the other of the original array's values.
Then use multisort to sort by text values (keys of the original array) and then by the numeric values (values of the original array).
SOLVED
After a little experimentation I discovered that array_multisort
does the trick nicely:
$tag = array();
$num = array();
foreach($arrTags as $key => $value){
$tag[] = $key;
$num[] = $value;
}
array_multisort($num, SORT_DESC, $tag, SORT_ASC, $arrTags);
:)