PHP multi-dimensional array sort

From: http://php.net/manual/en/function.usort.php

Example #4 usort() example using a closure to sort a multi-dimensional array

<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));

foreach ($array as $item) {
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>
The above example will output:
y, a
x, b
z, c

You can also sort multi-dimensional array for multiple values like as:

<?php
$arr = array(
    array('id'=>1, 'age'=>1, 'sex'=>6, 'name'=>'a'),
    array('id'=>2, 'age'=>3, 'sex'=>1, 'name'=>'c'),
    array('id'=>3, 'age'=>3, 'sex'=>1, 'name'=>'b'),
    array('id'=>4, 'age'=>2, 'sex'=>1, 'name'=>'d'),
);

print_r(arrayOrderBy($arr, 'age asc,sex asc,name desc'));

function arrayOrderBy(array &$arr, $order = null) {
    if (is_null($order)) {
        return $arr;
    }
    $orders = explode(',', $order);
    usort($arr, function($a, $b) use($orders) {
        $result = array();
        foreach ($orders as $value) {
            list($field, $sort) = array_map('trim', explode(' ', trim($value)));
            if (!(isset($a[$field]) && isset($b[$field]))) {
                continue;
            }
            if (strcasecmp($sort, 'desc') === 0) {
                $tmp = $a;
                $a = $b;
                $b = $tmp;
            }
            if (is_numeric($a[$field]) && is_numeric($b[$field]) ) {
                $result[] = $a[$field] - $b[$field];
            } else {
                $result[] = strcmp($a[$field], $b[$field]);
            }
        }
        return implode('', $result);
    });
    return $arr;
}
?>

output:
Array
(
    [0] => Array
        (
            [id] => 1
            [age] => 1
            [sex] => 6
            [name] => a
        )

    [1] => Array
        (
            [id] => 4
            [age] => 2
            [sex] => 1
            [name] => d
        )

    [2] => Array
        (
            [id] => 2
            [age] => 3
            [sex] => 1
            [name] => c
        )

    [3] => Array
        (
            [id] => 3
            [age] => 3
            [sex] => 1
            [name] => b
        )

)

Comments

7 responses to “PHP multi-dimensional array sort”