PHP: Move associative array element to beginning of array

前端 未结 6 455
轮回少年
轮回少年 2020-12-12 17:02

What would be the best method of moving any element of an associative array to the beginning of the array?

For example, say I have the following array:



        
6条回答
  •  既然无缘
    2020-12-12 17:23

    A bit late, but in case anyone needs it, I created this little snippet.

    function arr_push_pos($key, $value, $pos, $arr) 
    {
        $new_arr = array();
        $i = 1;
    
        foreach ($arr as $arr_key => $arr_value) 
        {
            if($i == $pos) 
                $new_arr[$key] = $value;
    
            $new_arr[$arr_key] = $arr_value;
    
            ++$i;
        }
    
        return $new_arr;
    }
    

    Just adjust it to suit your needs, or use it and unset the index to move. Works with associative arrays too.

提交回复
热议问题