Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array (which is nested inside of a multidimensional array) by a column


I think I should be using usort but I have no idea how to get that working.

Array
(
    [javascript] => Array
        (
            [core] => Array
                (
                    [0] => Array
                        (
                            [file] => /path/to/file.js
                            [weight] => 0
                        )

                    [1] => Array
                        (
                            [file] => /path/to/file2.js
                            [weight] => 1
                        )

                )

        )

)

I would like to sort the index of core by the weight value, other files and weights will be added and sorted after also.


Solution

  • usort($array['javascript']['core'], function($a, $b) {
        return $a['weight'] - $b['weight'];
    });