Friday, September 2, 2011

PHP - Sort multi-dimensional array by one key

The following function sorts an array (with the form shown in the example below) by any key and supports all PHP sort types (SORT_STRING, SORT_NUMERIC) and sort direction.
Oldies but goldies: as years passed by, the function served well and was allways there when needed.
Obs: array_multisort() PHP's native function can be also of use for similar jobs (mehr oder weniger), but the function presented below doesn't make use of it.

Example sort array by key:
$a = array(
    array('name' => 'John', 'salary' => 1245),
    array('name' => 'Paul', 'salary' => 1105),
    array('name' => 'Ralf', 'salary' => 2232),
);
// Sort by name (string)
$a1 = ar1_sort($a, 'name', SORT_STRING);
// Sort by salary (int)
$a2 = ar1_sort($a, 'name', SORT_NUMERIC, 'desc');

function ar1_sort($a, $sort_key, $sort_type = SORT_NUMERIC, $direction = 'asc') {
    $t = array();
    foreach($a as $k => $v) {
        $t[$k] = $v[$sort_key];
    }
    asort($t, $sort_type);
   
    $res = array();
    foreach($t as $k => $v) {
        $res[] = $a[$k];
    }
   
    if($direction == 'desc') {
        $res = array_reverse($res);
    }
   
    return $res;
}


No comments: