phparrayssortingmultidimensional-array

Sort a 2d array containing only one column and preserve first level keys


I need to sort an array like

$arrayName = array(
    0 => array('val' => 100),
    1 => array('val' => 75),
    3 => array('val' => 10),
    4 => array('val' => 15)
);

I need output like this

$arrayName = array(
    3 => array('val' => 10),
    4 => array('val' => 15),
    1 => array('val' => 75),
    0 => array('val' => 100)
);

Solution

  • asort() should work for you because it will:


    $arrayName = array(
        0 => array('val' => 100),
        1 => array('val' => 75),
        3 => array('val' => 10),
        4 => array('val' => 15)
    );
    asort($arrayName);
        
    print_r($arrayName);
    

    Output:

    Array (
        [3] => Array ( [val] => 10 )
        [4] => Array ( [val] => 15 )
        [1] => Array ( [val] => 75 )
        [0] => Array ( [val] => 100 )
    )
    

    For a descending sort, use arsort().