Move Value in PHP Array to the Beginning of the Array

前端 未结 12 1411
终归单人心
终归单人心 2020-12-10 02:52

I have a PHP array similar to this:

0 => \"red\",
1 => \"green\",
2 => \"blue\",
3 => \"yellow\"

I want to move yellow to index

12条回答
  •  没有蜡笔的小新
    2020-12-10 03:51

    This function will allow you to move an element to an arbitrary position within the array, while leaving the rest of the array untouched:

    function array_reorder($array, $oldIndex, $newIndex) {
        array_splice(
            $array,
            $newIndex,
            count($array),
            array_merge(
                array_splice($array, $oldIndex, 1),
                array_slice($array, $newIndex, count($array))
            )
        );
        return $array;
    }
    

    Hopefully the usage is fairly obvious, so this:

    $array = array('red','green','blue','yellow',);
    
    var_dump(
        array_reorder($array, 3, 0),
        array_reorder($array, 0, 3),
        array_reorder($array, 1, 3),
        array_reorder($array, 2, 0)
    );
    

    Will output this:

    array(4) {
      [0]=>
      string(6) "yellow"
      [1]=>
      string(3) "red"
      [2]=>
      string(5) "green"
      [3]=>
      string(4) "blue"
    }
    array(4) {
      [0]=>
      string(5) "green"
      [1]=>
      string(4) "blue"
      [2]=>
      string(6) "yellow"
      [3]=>
      string(3) "red"
    }
    array(4) {
      [0]=>
      string(3) "red"
      [1]=>
      string(4) "blue"
      [2]=>
      string(6) "yellow"
      [3]=>
      string(5) "green"
    }
    array(4) {
      [0]=>
      string(4) "blue"
      [1]=>
      string(3) "red"
      [2]=>
      string(5) "green"
      [3]=>
      string(6) "yellow"
    }
    

提交回复
热议问题