Moving up/down an item in the array by its value

前端 未结 3 1850
小鲜肉
小鲜肉 2021-01-13 02:41

I cannot find an effective solution on rearranging/swapping an array item by its value by shifting by - 1 or + 1. I\'m making an order on tables, i

相关标签:
3条回答
  • 2021-01-13 02:52
    $ret = array();
    for ($i = 0; $i < count($array); $i++) {
        if ($array[$i] == $desired_item_to_move && $i > 0) {
            $tmp = array_pop($ret);
            $ret[] = $array[$i];
            $ret[] = $tmp;
        } else {
            $ret[] = $array[$i];
        }
    }
    

    This will move up all instances of the desired element, putting the new array into $ret.

    0 讨论(0)
  • 2021-01-13 03:09

    Shifting up (assuming you've checked that the item is not already the first one):

    $item = $array[ $index ];
    $array[ $index ] = $array[ $index - 1 ];
    $array[ $index - 1 ] = $item;
    

    Shifting down:

    $item = $array[ $index ];
    $array[ $index ] = $array[ $index + 1 ];
    $array[ $index + 1 ] = $item;
    
    0 讨论(0)
  • 2021-01-13 03:10

    A useful function for the more general problem of moving an element of an array from one position to another:

    function array_move(&$a, $oldpos, $newpos) {
        if ($oldpos==$newpos) {return;}
        array_splice($a,max($newpos,0),0,array_splice($a,max($oldpos,0),1));
    }
    

    This can then be used to solve the specific problem in the original question:

    // shift up
    array_move($array,$index,$index+1);
    // shift down
    array_move($array,$index,$index-1);
    

    Note, there's no need to check whether or not you're already at the start/end of the array. Note also, this function does not preserve the array keys - moving elements while preserving keys is more fiddly.

    0 讨论(0)
提交回复
热议问题