Move an array element to a new index in PHP

后端 未结 9 1850
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 04:47

I\'m looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt ne

9条回答
  •  自闭症患者
    2020-12-03 04:51

    Take a look at this thread which describes a similar problem. The following solution is provided:

    /**
     * Move array element by index.  Only works with zero-based,
     * contiguously-indexed arrays
     *
     * @param array $array
     * @param integer $from Use NULL when you want to move the last element
     * @param integer $to   New index for moved element. Use NULL to push
     * 
     * @throws Exception
     * 
     * @return array Newly re-ordered array
     */
    function moveValueByIndex( array $array, $from=null, $to=null )
    {
      if ( null === $from )
      {
        $from = count( $array ) - 1;
      }
    
      if ( !isset( $array[$from] ) )
      {
        throw new Exception( "Offset $from does not exist" );
      }
    
      if ( array_keys( $array ) != range( 0, count( $array ) - 1 ) )
      {
        throw new Exception( "Invalid array keys" );
      }
    
      $value = $array[$from];
      unset( $array[$from] );
    
      if ( null === $to )
      {
        array_push( $array, $value );
      } else {
        $tail = array_splice( $array, $to );
        array_push( $array, $value );
        $array = array_merge( $array, $tail );
      }
    
      return $array;
    }
    

提交回复
热议问题