考虑以下列表:
$list = array(
0 => A,
1 => X,
2 => B,
3 => Z,
4 => K,
5 => M
);
我想将 A 的位置从 0 更改为 2 然后 $list 变为:
$list = array(
0 => X,
1 => B,
2 => A,
3 => Z,
4 => K,
5 => M
);
以下代码是我迄今为止尝试过的,还有其他使用数组函数的方法吗?或任何更短的方式?
<?php
$list = array(0 => 'A', 1 => 'X', 2 => 'B', 3 => 'Z', 4 => 'K', 5 => 'M');
function change_position($oldposition, $newposition, $list){
echo "Changing $oldposition to $newposition :\n";
foreach($list as $k => $v){
if($oldposition < $newposition){
if( $k < $oldposition ){
$newlist[$k] = $list[$k];
}
if($k >= $oldposition && $k < $newposition){
$newlist[$k] = $list[$k+1];
}
if($k == $newposition){
$newlist[$k] = $list[$oldposition];
}
if($k > $newposition){
$newlist[$k] = $list[$k];
}
}
if($oldposition > $newposition){
if( $k > $oldposition ){
$newlist[$k] = $list[$k];
}
if($k <= $oldposition && $k > $newposition){
$newlist[$k] = $list[$k-1];
}
if($k == $newposition){
$newlist[$k] = $list[$oldposition];
}
if($k < $newposition){
$newlist[$k] = $list[$k];
}
}
}
return $newlist;
}
echo '<pre>';
print_r($list);
print_r(change_position(5, 0, $list));
print_r(change_position(0, 5, $list));
?>
输出:
Array
(
[0] => A
[1] => X
[2] => B
[3] => Z
[4] => K
[5] => M
)
Changing 5 to 0 :
Array
(
[0] => M
[1] => A
[2] => X
[3] => B
[4] => Z
[5] => K
)
Changing 0 to 5 :
Array
(
[0] => X
[1] => B
[2] => Z
[3] => K
[4] => M
[5] => A
)