Moving array element to top in PHP

后端 未结 5 1974
陌清茗
陌清茗 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条回答
  •  感情败类
    2020-12-05 16:13

    You can achieve that this way:

    $arr = array(
        'a1'=>'1',
        'a2'=>'2'
    );
    
    end($arr);
    
    $last_key     = key($arr);
    $last_value   = array_pop($arr);
    $arr          = array_merge(array($last_key => $last_value), $arr);
    
    /*
        print_r($arr);
    
        will output (this is tested):
        Array ( [a2] => 2 [a1] => 1 )
    */

提交回复
热议问题