Search code examples
phparrayssortingmultidimensional-array

How to sort multi-dimensional array by a column and preserve the non-numeric first level keys


How to sort this array by pos attribute even though keys (name, store_id, product etc.)

[Attributes] => Array
(
    [name] => Array
        (
            [pos] => 30
        )

    [store_id] => Array
        (
            [pos] => 10
        )

    [product] => Array
        (
            [pos] => 20
        )

)

Edit: performance is important of course.


Solution

  • You could use uasort() which lets you define your sorting logic and also maintains your associative indexes. Please note that it changes your original array and only returns a boolean based on success.

    uasort($your_array, function($a, $b) {
        return $a['pos'] > $b['pos'];
    });
    

    My example works >= PHP 5.3 , but for older versions you can use a normal compare function as well.

    See uasort() Documentation for details.