Search code examples
phparrayssortingmultidimensional-array

sort second level Array


i have this Array:

Array
(
    [0] => Array
        (
            [kw] => 46
            [anzahl_betten] => 100
        )

    [1] => Array
        (
            [kw] => 47
            [anzahl_betten] => 100
        )

    [2] => Array
        (
            [kw] => 45
            [anzahl_betten] => 100
        )

)

I want to sort it in "kw" order. I then want to go through the Array with foreach($array as $output) und the Array with kw 45 should be Array[0].


Solution

  • Use usort() for that:

    //$array is your array
    usort($array, function($x, $y)
    {
       return $x['kw']<$y['kw']?-1:$x['kw']!=$y['kw'];
    });