将 PHP 数组中的值移动到数组的开头
我有一个类似于下面的PHP数组:
0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"
我想将黄色移动到索引 0。我该怎么做?
编辑:我的问题是如何将这些元素中的任何一个移动到开头?如何将绿色移至索引 0,或将蓝色移至索引 0?这个问题并不完全是关于将最后一个元素移到开头。
我有一个类似于下面的PHP数组:
0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"
我想将黄色移动到索引 0。我该怎么做?
编辑:我的问题是如何将这些元素中的任何一个移动到开头?如何将绿色移至索引 0,或将蓝色移至索引 0?这个问题并不完全是关于将最后一个元素移到开头。
对我来说,这似乎是最简单的方法。您可以将任何位置移动到开头,而不仅仅是最后一个位置(在此示例中,它将蓝色移动到开头)。
$colours = array("red", "green", "blue", "yellow");
$movecolour = $colours[2];
unset($colours[2]);
array_unshift($colours, $movecolour);
可能是最直接的方法
array_unshift( $arr, array_pop( $arr ) );
根据你的评论“我如何从数组中获取任何一个下标并将其移动到开头”,我上面的答案并不能完全满足该请求 - 它只能通过将最后一个元素移动到0索引来工作。
但是,此函数确实满足该请求
/**
* 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;
}
并且,在使用中
$arr = array( 'red', 'green', 'blue', 'yellow' );
echo implode( ',', $arr ); // red,green,blue,yellow
// Move 'blue' to the beginning
$arr = moveValueByIndex( $arr, 2, 0 );
echo implode( ',', $arr ); // blue,red,green,yellow