Move an array element to a new index in PHP

后端 未结 9 1868
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 04:47

I\'m looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt ne

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 05:11

    Arrays in PHP are not actual array in the C sens but associative arrays. But the way to move a value from an index to another is quiet straight forward and is the same as in C++:

    Copy the value to move to a temporary buffer, translate all the elements to crush the empty spot at the source position and in the same free up a spot on the destination position. Put the backup value in the destination spot.

    function moveElement ($a , $i , $j)
    {
          $tmp =  $a[$i];
          if ($i > $j)
          {
               for ($k = $i; $k > $j; $k--) {
                    $a[$k] = $a[$k-1]; 
               }        
          }
          else
          { 
               for ($k = $i; $k < $j; $k++) {
                    $a[$k] = $a[$k+1];
               }
          }
          $a[$j] = $tmp;
          return $a;
    }
    
    
    $a = array(0, 1, 2, 3, 4, 5);
    print_r($a);
    
    $a = moveElement($a, 1, 4);
    echo ('1 ->  4');
    print_r($a);
    
    
    $a = moveElement($a, 5, 0);
    echo ('5 ->  0' );
    print_r($a);
    

    Output:

    Array
    (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 5
    )
    1 ->  4Array
    (
        [0] => 0
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 1
        [5] => 5
    )
    5 ->  0Array
    (
        [0] => 5
        [1] => 0
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 1
    )
    

    You'll need to add some Exception handling to have a complete code.

提交回复
热议问题