Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Jan Roels
Jan Roels
2,308 Points

Sort array float values

Hi,

I get the following output from my array:

array (size=381)
  0 => 
    array (size=2)
      'Name' => string 'apple' (length=6)
      'Number' => float 0.368844763
  1 => 
    array (size=2)
      'Name' => string 'Blueberry' (length=8)
      'Number' => float 5.59E-6
  2 => 
    array (size=2)
      'Name' => string 'Cinnamon' (length=5)
      'Number' => float -0.0006947
  3 => 
    array (size=2)
      'Name' => string 'Date' (length=10)
      'Number' => float 0.001584453
...
...
...

I want the array to be sorted with the highest 'Number' value first. What's the best way to do this?

2 Answers

Andrew McCormick
Andrew McCormick
17,729 Points

Taken from php.net

function sksort(&$array, $subkey="Number", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}
Jan Roels
Jan Roels
2,308 Points

Awesome, works like a charm!