【发布时间】: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)?