Move an array element to a new index in PHP

后端 未结 9 1857
佛祖请我去吃肉
佛祖请我去吃肉 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 04:54

    The solution from hakre with two array_splice commands doesn't work with named arrays. The key of the moved element will be lost.

    Instead you can splice the array two times and merge the parts.

    function moveElement(&$array, $a, $b) {
        $p1 = array_splice($array, $a, 1);
        $p2 = array_splice($array, 0, $b);
        $array = array_merge($p2,$p1,$array);
    }
    

    How does it work:

    • First: remove/splice the element from the array
    • Second: splice the array into two parts at the position you want to insert the element
    • Merge the three parts together

    Example:

    $fruits = array(
        'bananas'=>'12', 
        'apples'=>'23',
        'tomatoes'=>'21', 
        'nuts'=>'22',
        'foo'=>'a',
        'bar'=>'b'
    );
    
    moveElement($fruits, 1, 3);
    
    // Result
    ['bananas'=>'12', 'tomatoes'=>'21', 'nuts'=>'22', 'apples'=>'23', 'foo'=>'a', 'bar'=>'b']
    

提交回复
热议问题