note 22542 deleted from ref.array by didou
| From: | didou@php.net | Date: | Sun, 18 May 2003 01:20:20 +0000 |
| Subject: | note 22542 deleted from ref.array by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-48316@lists.php.net to get a copy of this message | ||
Note Submitter: b.parish@linst.ac.uk
----
<?
$myarray = array();
$myarray[1] = 1;
$myarray[2] = 2;
$myarray[3] = 3;
$myarray[4] = 4;
// I want to move $myarray[2] to the 4th position.
$ordered_array = reposition($myarray, 2,4);
foreach($ordered_array as $key=>$value){
echo "ordered_array[$key] = $value";
}
?>
// The output of this function will be:
ordered_array[1] = 1
ordered_array[2] = 4
ordered_array[3] = 2
ordered_array[4] = 3
<?
function reposition($myarray,$myarray_key,$newpos){
$oldpos = $myarray[$myarray_key];
foreach($myarray as $key=>$value){
if($key==$myarray_key){
$myarray[$key] = $newpos;
}else{
if($oldpos>=$newpos){ // It's moving up the array
// Values following it will go down (lower position)
if($myarray[$key]<=$oldpos && $myarray[$key]>=$newpos){
$myarray[$key]++;
}
}else{ // It's moving down the array
// Values preceding it will go up (higher position)
if($myarray[$key]>=$oldpos && $myarray[$key]<=$newpos){
$myarray[$key]--;
}
}
}
}
return $myarray;
}
?>