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

后端 未结 5 675
独厮守ぢ
独厮守ぢ 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条回答
  •  Happy的楠姐
    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

提交回复
热议问题