Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by values of one column


I'm having some problems wrapping my head around how to do this. I have an array in PHP

    array(131) {
     ["BLANF     "]=>
      array(3) {
        ["line_3"]=>
        string(4) "3.92"
        ["line_1"]=>
        string(1) "6"
        ["line_2"]=>
        string(2) "14"
      }
      ["BLOOH     "]=>
      array(3) {
        ["line_3"]=>
        string(4) "2.00"
        ["line_1"]=>
        string(1) "20"
        ["line_2"]=>
        string(1) "6"
      }

}

That I need to sort based on the value of line_1.


Solution

  • You have to create a custom comparison function for your array and employ it with uasort() to maintain the indices of the array.

    Here is how you can use uasort() to sort by line_1... It's simple to change to sort by any other key in the nested array.

    <?php
    
      // The custom comparison function
    function cmp($a, $b)            
    {
        if ($a["line_1"] == $b["line_1"]) {
            return 0;
        }
        return ($a["line_1"] < $b["line_1"]) ? -1 : 1;
    }
    
      // Sort the array using your custom comparison
    uasort($array, 'cmp');
    
      // Make sure we got the right result
    print_r($array);
    ?>
    

    Live Example

    (I changed the line_1 numbers so that the sort actually does something)

    In this case PHP will juggle the types for you, but you should watch out for the fact that you have strings and are converting them to numbers. If you're not sure what will happen then cast the strings to floats or ints. This is important since, PHP can compare strings alphabetically with the comparison operators.... so, if there's any chance that a letter or comma or something can sneak into your array value then you can type cast to an int ( (int) $a["line_1"] ) or a float ( (float) $a["line_1"] ).