note 75410 added to function.sort

From: Date: Mon, 28 May 2007 17:29:59 +0000
Subject: note 75410 added to function.sort
Groups: php.notes 
Request: Send a blank email to php-notes+get-126983@lists.php.net to get a copy of this message
Here's my fixed up msort array. What it does is goes through a multidimensional array, and sorts it by the desired key (defaulting to 'id'). So, for example, if you have an array like: array[0]['value'] = "statement 2" array[0]['id'] = "2" array[1]['value'] = "statement 3" array[1]['id'] = "3" array[2]['value'] = "statement 1" array[2]['id'] = "1" it would rearrange and return the array to be like: array[0]['value'] = "statement 1" array[0]['id'] = "1" array[1]['value'] = "statement 2" array[1]['id'] = "2" array[2]['value'] = "statement 3" array[2]['id'] = "3" The 'id' index can start at any point, and any array item missing the id index will be added to the end. <?php function msort($array, $id="id") { $temp_array = array(); while(count($array)>0) { $lowest_id = 0; $index=0; foreach ($array as $item) { if (isset($item[$id]) && $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)); } return $temp_array; } ?> Ex: <?php //oh no, this is not in the ordered by id!! $data[] = array("item"=>"item 4"); $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) ); //just msort it! /* outputs 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 3 => array 'item' => 'item 4' (length=6) */ ?> ---- Server IP: 216.235.15.211 Probable Submitter: 204.244.149.125 ---- Manual Page -- http://www.php.net/manual/en/function.sort.php Edit -- https://master.php.net/note/edit/75410 Del: integrated -- https://master.php.net/note/delete/75410/integrated Del: useless -- https://master.php.net/note/delete/75410/useless Del: bad code -- https://master.php.net/note/delete/75410/bad+code Del: spam -- https://master.php.net/note/delete/75410/spam Del: non-english -- https://master.php.net/note/delete/75410/non-english Del: in docs -- https://master.php.net/note/delete/75410/in+docs Del: other reasons-- https://master.php.net/note/delete/75410 Reject -- https://master.php.net/note/reject/75410 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#126983) next »