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

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

提交回复
热议问题