Moving array element to top in PHP

后端 未结 5 1978
陌清茗
陌清茗 2020-12-05 15:27
$arr = array(
    \'a1\'=>\'1\',
    \'a2\'=>\'2\'
);

I need to move the a2 to the top, as well as keep the a2 as a key how woul

5条回答
  •  猫巷女王i
    2020-12-05 16:16

    Here is a solution which works correctly both with numeric and string keys:

    function move_to_top(&$array, $key) {
        $temp = array($key => $array[$key]);
        unset($array[$key]);
        $array = $temp + $array;
    }
    

    It works because arrays in PHP are ordered maps.
    Btw, to move an item to bottom use:

    function move_to_bottom(&$array, $key) {
        $value = $array[$key];
        unset($array[$key]);
        $array[$key] = $value;
    }
    

提交回复
热议问题