Forum Moderators: coopster

Message Too Old, No Replies

Properly sorting mixed multidimensional array

         

IntegrityWebDev

4:13 pm on Mar 1, 2011 (gmt 0)

10+ Year Member



I have a multidimensional array called "distance" where the first element is a float, the 2nd is a string, as such:
[12.42345, "Location A"]
[2.98765, "Location B"]
[6.12344, "Location C"]

I need to sort this for the lowest # in the first column, but I need the info from the 2nd column.

It *SEEMS* this works:
sort($distance);


Because when I var_dump distance before and after the sort, everything is correct.

Once I do the sort, $distance[0][1] should always have the value I need to get (after the sort is done).

In the PHP manual, on the page for Sort it says the following:
Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results.


I have a small dataset that I am working with but I need to ensure my results are correct.

Is there a better way to go about this?

Thanks,
Chris

lammert

4:33 pm on Mar 1, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The warning for mixed type values is not for your situation. It is where different types like integers, floats and strings are present in the same column of the array. In some language constructs PHP will do automatic type casting when comparing values of different types, and this may not always give the result you expect. As long as you are sure that only floats are present, no unpredictable results will occur.

IntegrityWebDev

5:48 pm on Mar 1, 2011 (gmt 0)

10+ Year Member



Ah gotcha...
same column, same type = OK
same column, diff types = things get wonky

Thanks!