Move an array element to a new index in PHP

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

    A function that preserves keys:

    function moveElementInArray($array, $toMove, $targetIndex) {
        if (is_int($toMove)) {
            $tmp = array_splice($array, $toMove, 1);
            array_splice($array, $targetIndex, 0, $tmp);
            $output = $array;
        }
        elseif (is_string($toMove)) {
            $indexToMove = array_search($toMove, array_keys($array));
            $itemToMove = $array[$toMove];
            array_splice($array, $indexToMove, 1);
            $i = 0;
            $output = Array();
            foreach($array as $key => $item) {
                if ($i == $targetIndex) {
                    $output[$toMove] = $itemToMove;
                }
                $output[$key] = $item;
                $i++;
            }
        }
        return $output;
    }
    
    $arr1 = Array('a', 'b', 'c', 'd', 'e');
    $arr2 = Array('A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e');
    
    print_r(moveElementInArray($arr1, 3, 1));
    print_r(moveElementInArray($arr2, 'D', 1));
    

    Ouput:

    Array
    (
        [0] => a
        [1] => d
        [2] => b
        [3] => c
        [4] => e
    )
    Array
    (
        [A] => a
        [D] => d
        [B] => b
        [C] => c
        [E] => e
    )
    

提交回复
热议问题