note 75381 added to function.sort
| From: | alishahnovin at hotmail dot com | Date: | Fri, 25 May 2007 23:11:51 +0000 |
| Subject: | note 75381 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126930@lists.php.net to get a copy of this message | ||
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up
with...
<?php
function msort($array, $id="id") {
$temp_array = array();
while(count($array)>0) {
$lowest_id = 0;
$index=0;
foreach ($array as $item) {
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", "id"=>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)
'id' => 4
*/
?>
----
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/75381
Del: integrated -- https://master.php.net/note/delete/75381/integrated
Del: useless -- https://master.php.net/note/delete/75381/useless
Del: bad code -- https://master.php.net/note/delete/75381/bad+code
Del: spam -- https://master.php.net/note/delete/75381/spam
Del: non-english -- https://master.php.net/note/delete/75381/non-english
Del: in docs -- https://master.php.net/note/delete/75381/in+docs
Del: other reasons-- https://master.php.net/note/delete/75381
Reject -- https://master.php.net/note/reject/75381
Search -- https://master.php.net/manage/user-notes.php