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.
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 byline_1… It’s simple to change to sort by any other key in the nested array.Live Example
(I changed the
line_1numbers 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"]).