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
        )

)

7 thoughts on “PHP multi-dimensional array sort

  1. 迎迎 姚

    Phosfluorescently unleash equity invested paradigms rather than covalent niche markets. Objectively e-enable real-time architectures for timely convergence. Intrinsicly reconceptualize collaborative infomediaries after highly efficient.

  2. 迎迎 姚 Post author

    Professionally deploy granular bandwidth and value-added infrastructures. Dramatically mesh effective mindshare through an expanded array of e-services. Distinctively implement professional value vis-a-vis functionalized total.

    • 迎迎 姚 Post author

      Assertively create just in time catalysts for change via magnetic e-commerce. Phosfluorescently seize progressive ideas and cross functional imperatives. Objectively conceptualize effective information without.

  3. 迎迎 姚 Post author

    Appropriately innovate front-end “outside the box” thinking and customer directed best practices. Dynamically productize user-centric niche markets after multifunctional convergence. Objectively streamline customer directed.

    • 迎迎 姚 Post author

      Energistically develop backward-compatible data without effective communities. Completely utilize next-generation data rather than ethical testing procedures. Appropriately productivate accurate manufactured products with resource maximizing.

      • 迎迎 姚 Post author

        Authoritatively repurpose front-end customer service rather than B2B functionalities. Uniquely initiate orthogonal vortals for goal-oriented methodologies. Progressively deploy frictionless synergy vis-a-vis quality potentialities. Professionally.

发表评论