Php 将数组索引移到前面的最快方法

Php 将数组索引移到前面的最快方法,php,arrays,indexing,Php,Arrays,Indexing,我目前在我的代码中有这个缺陷。在过滤掉数组中的一些元素后,我将得到以下结果 $myArray = //Note that index 0 till 3 doesn't exist in this array [4] => 'elementAtFourthIndex' [5] => 'elementAtFifthIndex' [6] => 'elementAtSixthIndex' 尽管我希望获得如下数组: $myArray = [0] =>

我目前在我的代码中有这个缺陷。在过滤掉数组中的一些元素后,我将得到以下结果

$myArray =
   //Note that index 0 till 3 doesn't exist in this array
   [4] => 'elementAtFourthIndex'
   [5] => 'elementAtFifthIndex'
   [6] => 'elementAtSixthIndex'
尽管我希望获得如下数组:

$myArray =
   [0] => 'elementAtZeroIndex'
   [1] => 'elementAtFirstIndex'
   [2] => 'elementAtSecondIndex'
StackOverflow上的其他人已经在另一个主题中提供了此解决方案,但这似乎太难了,因为有些事情很简单:

/**
 * 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;
}

使用数组值可以完美地工作,正如Nigel Ren作为注释回答的那样

使用数组值可以完美地工作,正如Nigel Ren作为注释回答的一样

数组值($myArray)
数组值($myArray)