views:

60

answers:

2

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. In PHP Thanks Zachary

+3  A: 

Use uasort by providing a comparison callback function that compares the values of the appropriate lines.

Victor Nicollet
Your solution is very efficient.
Michael Eakins
@Peter Ajtai: In this particular case, the keys seem to be meaningful, so `uasort` would be required to conserve them.
Victor Nicollet
Thanks. Oops...
Peter Ajtai
+2  A: 

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"] ).

Peter Ajtai
1200 elements is not super big, im sure PHP can handle that
RobertPitt
Helps when you test the code and figure out what your looking at. This works great. Thank you
arkansasonline
heres a small test for you: http://codepad.org/Wayx759t
RobertPitt