PHP: Move associative array element to beginning of array

前端 未结 6 457
轮回少年
轮回少年 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:26

    There's a function in the comments of the PHP manual for array_unshift which can be used to add an element, with key, to the beginning of an array:

    function array_unshift_assoc(&$arr, $key, $val)
    {
        $arr = array_reverse($arr, true);
        $arr[$key] = $val;
        return array_reverse($arr, true);
    }
    

    Unset the element and reinsert it again with the above function:

    $tmp = $myArray['one'];
    unset($myArray['one']);
    $myArray = array_unshift_assoc($myArray, 'one', $tmp);
    

    A more general approach may be to use uksort to sort your array by keys and provide a sorting function of your own.

提交回复
热议问题