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

前端 未结 3 1871
小鲜肉
小鲜肉 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 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;
    

提交回复
热议问题