【问题标题】:Fastest way to shift array indexes to front [duplicate]将数组索引移到前面的最快方法[重复]
【发布时间】:2020-04-01 09:40:06
【问题描述】:

我的代码中目前存在此功能。过滤掉数组中的一些元素后,我得到以下结果。

$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;
}

【问题讨论】:

  • array_values($myArray)?

标签: php arrays indexing


【解决方案1】:

使用 array_values 效果很好,正如 Nigel Ren 作为评论所回答的那样

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 2018-02-18
    • 2010-11-12
    • 1970-01-01
    • 2014-05-20
    • 2021-05-15
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多