How do I move an array element with a known key to the end of an array in PHP?

后端 未结 5 663
独厮守ぢ
独厮守ぢ 2020-12-03 04:19

Having a brain freeze over a fairly trivial problem. If I start with an array like this:

$my_array = array(
                  \'monkey\'  => array(...),
          


        
相关标签:
5条回答
  • 2020-12-03 04:39

    You can implement some basic calculus and get a universal function for moving array element from one position to the other.

    For PHP it looks like this:

    function magicFunction ($targetArray, $indexFrom, $indexTo) { 
        $targetElement = $targetArray[$indexFrom]; 
        $magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom); 
    
        for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){ 
            $targetArray[$Element] = $targetArray[$Element + $magicIncrement]; 
        } 
    
        $targetArray[$indexTo] = $targetElement; 
    }
    

    Check out "moving array elements" at "gloommatter" for detailed explanation.

    http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html

    0 讨论(0)
  • 2020-12-03 04:41

    The only way I can think to do this is to remove it then add it:

    $v = $my_array['monkey'];
    unset($my_array['monkey']);
    $my_array['monkey'] = $v;
    
    0 讨论(0)
  • 2020-12-03 04:46

    Contributing to the accepted reply - for the element not to be inserted into the same position, but to be placed at the end of the array:

    $v = $my_array['monkey'];
    unset($my_array['monkey']);
    

    instead of:

    $my_array['monkey'] = $v;
    

    use:

    array_push($my_array, $v);
    
    0 讨论(0)
  • 2020-12-03 05:04

    array_shift is probably less efficient than unsetting the index, but it works:

    $my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
    $my_array['monkey'] = array_shift($my_array);
    print_r($my_array);
    

    Another alternative is with a callback and uksort:

    uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
    

    You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.

    0 讨论(0)
  • 2020-12-03 05:04

    I really like @Gordon's answer above for it's elegance as a one liner, but it only works if the key is at the beginning. Here's another one liner that will work for a key in any position:

    $arr = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
    $arr += array_splice($arr,array_search('giraffe',array_keys($arr)),1);
    

    EDIT: Beware, this fails with numeric keys.

    0 讨论(0)
提交回复
热议问题