note 76547 added to function.sort

From: Date: Thu, 19 Jul 2007 23:16:20 +0000
Subject: note 76547 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-128749@lists.php.net to get a copy of this message
Someone asked me if the msort I posted below can do a sort by descending... (as it sorts by ascending...smallest to greatest). It's a simple fix with an extra param, and then an array_reverse...but for the lazy, here you are: <?php function msort($array, $id="id", $sort_ascending=true) { $temp_array = array(); while(count($array)>0) { $lowest_id = 0; $index=0; foreach ($array as $item) { if (isset($item[$id])) { if ($array[$lowest_id][$id]) { if ($item[$id]<$array[$lowest_id][$id]) { $lowest_id = $index; } } } $index++; } $temp_array[] = $array[$lowest_id]; $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1)); } if ($sort_ascending) { return $temp_array; } else { return array_reverse($temp_array); } } ?> <?php //oh no, this is not in the ordered by id!! $data[] = array("item"=>"item 1", "id"=>1); $data[] = array("item"=>"item 3", "id"=>3); $data[] = array("item"=>"item 2", "id"=>2); var_dump( msort($data, "id", false) ); //just msort it...greatest to smallest var_dump( msort($data, "id") ); //just msort it...smallest to greatest /* outputs array 0 => array 'item' => 'item 3' (length=6) 'id' => 3 1 => array 'item' => 'item 2' (length=6) 'id' => 2 2 => array 'item' => 'item 1' (length=6) 'id' => 1 array 0 => array 'item' => 'item 1' (length=6) 'id' => 1 1 => array 'item' => 'item 2' (length=6) 'id' => 2 2 => array 'item' => 'item 3' (length=6) 'id' => 3 */ ?> ---- Server IP: 66.207.199.35 Probable Submitter: 204.244.149.125 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/76547 Del: integrated -- https://master.php.net/note/delete/76547/integrated Del: useless -- https://master.php.net/note/delete/76547/useless Del: bad code -- https://master.php.net/note/delete/76547/bad+code Del: spam -- https://master.php.net/note/delete/76547/spam Del: non-english -- https://master.php.net/note/delete/76547/non-english Del: in docs -- https://master.php.net/note/delete/76547/in+docs Del: other reasons-- https://master.php.net/note/delete/76547 Reject -- https://master.php.net/note/reject/76547 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#128749) next »