PHP 8.3.22 Released!

Voting

: min(four, five)?
(Example: nine)

The Note You're Voting On

alishahnovin at hotmail dot com
18 years ago
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

*/

?>

<< Back to user notes page

To Top