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:05

    A lot of good answers. Here's a simple one built on the answer by @RubbelDeCatc. The beauty of it is that you only need to know the array key, not its current position (before repositioning).

    /**
     * Reposition an array element by its key.
     *
     * @param array      $array The array being reordered.
     * @param string|int $key They key of the element you want to reposition.
     * @param int        $order The position in the array you want to move the element to. (0 is first)
     *
     * @throws \Exception
     */
    function repositionArrayElement(array &$array, $key, int $order): void
    {
        if(($a = array_search($key, array_keys($array))) === false){
            throw new \Exception("The {$key} cannot be found in the given array.");
        }
        $p1 = array_splice($array, $a, 1);
        $p2 = array_splice($array, 0, $order);
        $array = array_merge($p2, $p1, $array);
    }
    

    Straight forward to use:

    $fruits = [
        'bananas'=>'12', 
        'apples'=>'23',
        'tomatoes'=>'21', 
        'nuts'=>'22',
        'foo'=>'a',
        'bar'=>'b'
    ];
    
    repositionArrayElement($fruits, "foo", 1);
    
    var_export($fruits);
    
    /** Returns
    array (
      'bananas' => '12',
      'foo' => 'a', <--  Now moved to position #1
      'apples' => '23',
      'tomatoes' => '21',
      'nuts' => '22',
      'bar' => 'b',
    )
    **/
    

    Works on numeric arrays also:

    $colours = ["green", "blue", "red"];
    
    repositionArrayElement($colours, 2, 0);
    
    var_export($colours);
    
    /** Returns
    array (
      0 => 'red', <-- Now moved to position #0
      1 => 'green',
      2 => 'blue',
    )
    */
    

    Demo

提交回复
热议问题