php associative array key order (not sort)

前端 未结 5 816
余生分开走
余生分开走 2020-12-17 10:38

My array:

$data = array(\'two\' => 2, \'one\' => 1, \'three\' => 3);

Now, with when I iterate the array, the first value that wil

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 11:06

    Take a look at daniele centamore's comment on PHP's array_splice() function, where he provides a couple of functions for moving the elements in an non-associative array.

    $index) && ($index>0)){
                     array_splice($new_array, $index-1, 0, $input[$index]);
                     array_splice($new_array, $index+1, 1);
                 } 
    
           return $new_array;
    }
    
    function moveDown($input,$index) {
           $new_array = $input;
    
           if(count($new_array)>$index) {
                     array_splice($new_array, $index+2, 0, $input[$index]);
                     array_splice($new_array, $index, 1);
                 } 
    
           return $new_array;
    }  
    
    $input = array("red", "green", "blue", "yellow");
    
    $newinput = moveUp($input, 2);
    // $newinput is array("red", "blue", "green", "yellow")
    
    $input = moveDown($newinput, 1);
    // $input is array("red", "green", "blue", "yellow")
    
    ?>
    

提交回复
热议问题