0

考虑以下列表:

$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
)
4

1 回答 1

2

只需使用array_splice

function move_element(&$array, $element, $position)
{
    $key = array_search($element, $array, true);
    if ($key === false) {
        return;
    }

    array_splice($array, array_search($key, array_keys($array)), 1);
    array_splice($array, $position, 0, $element);
}

您的示例将通过

move_element($list, 'A', 2);

如果您不想将目标指定为值,而是指定为位置,则更容易:

function move_element(&$array, $from, $to)
{
    $removed = array_splice($array, $from, 1);
    array_splice($array, $to, 0, $removed);
}

move_element($list, 0, 2);
于 2013-03-02T20:56:42.743 回答