PHP 8.5.0 Alpha 4 available for testing

Voting

: four plus five?
(Example: nine)

The Note You're Voting On

mike at clear-link dot com
17 years ago
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
if (
$valrev) { arsort($array); } else { asort($array); }
$vals = array_count_values($array);
$i = 0;
foreach (
$vals AS $val=>$num) {
$first = array_splice($array,0,$i);
$tmp = array_splice($array,0,$num);
if (
$keyrev) { krsort($tmp); } else { ksort($tmp); }
$array = array_merge($first,$tmp,$array);
unset(
$tmp);
$i = $num;
}
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
[
pe] => 1
[ca] => 1
[ce] => 1
[cb] => 2
[pa] => 2
)
Array
(
[
ca] => 1
[ce] => 1
[pe] => 1
[cb] => 2
[pa] => 2
)
Array
(
[
cb] => 2
[pa] => 2
[ca] => 1
[ce] => 1
[pe] => 1
)
Array
(
[
pa] => 2
[cb] => 2
[pe] => 1
[ce] => 1
[ca] => 1
)

<< Back to user notes page

To Top