This is my Mulit-Dim array:

Array (
[0] => Array ( [latitude] => 28.066284 [longitude] => -82.216304 [dist] => 16.8467090256 )
[1] => Array ( [latitude] => 28.068117 [longitude] => -82.299313 [dist] => 14.7736745307 )
[2] => Array ( [latitude] => 27.938454 [longitude] => -81.990367 [dist] => 23.7279350068 )
[3] => Array ( [latitude] => 27.843002 [longitude] => -82.728622 [dist] => 21.9764064392 )
[4] => Array ( [latitude] => 28.157392 [longitude] => -82.015702 [dist] => 29.6361789323 )
)

I'd like to sort this by the [dist] column. How do I do this using the PHP sort commands? I've been trying the array_multisort() command, but I can't seem to get it.

Thanks!

    You could use [man]usort[/man] and write a function that compares the 'dist' part of two arrays.

      Weedpacket wrote:

      You could use [man]usort[/man] and write a function that compares the 'dist' part of two arrays.

      Great! That works smooth except one thing ...it's sorting based on string value and not a numerical value so I'm getting:

      22
      23.4
      31
      40.4
      8.1

      instead of:

      8.1
      22
      23.4
      31
      40.4

      How do I fix this? I tried plugging in floatval() like this:

      function cmp_dist($a, $b)
      {
         return strcmp(floatval($a["dist"]), floatval($b["dist"]));
      }

      But that didn't work. Any ideas?

      Thanks!

        foreach ($array as $key => $value) {
            $tmp[] = $value['dist'];
        }
        array_multisort($tmp, SORT_NUMERIC, $array);
          Installer wrote:

          [what he said]

          That's the bit I always disliked about array_multisort - the need for a temporary array.

          tguill wrote:

          return strcmp(floatval($a["dist"]), floatval($b["dist"]));

          Well if they're floats then you wouldn't want to use a string comparison any more, would you? You just need their difference.

            ...the need for a temporary array.

            That's a good point, although with "usort()" you need two effectively temporary variables, repeated n times.

              Yeah, but they're only single pointers to existing elements, and they're gone by the end of the call. It's not a matter of constructing an entire array that is left hanging around later.

                2 years later
                Installer wrote:
                foreach ($array as $key => $value) {
                    $tmp[] = $value['dist'];
                }
                array_multisort($tmp, SORT_NUMERIC, $array);

                Thanks for this ;]

                  You resurrected a thread that was dormant for well over a year, but a solution to tguill's problem that uses usort() is:

                  usort($array, create_function('$a, $b', 'return $a["dist"] - $b["dist"];'));
                    Write a Reply...