将 PHP 数组中的值移动到数组的开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4126502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:03:36  来源:igfitidea点击:

Move Value in PHP Array to the Beginning of the Array

phparrays

提问by Jarred

I have a PHP array similar to this:

我有一个类似这样的 PHP 数组:

0 => "red",
1 => "green",
2 => "blue",
3 => "yellow"

I want to move yellow to index 0. How do I do this?

我想将黄色移动到索引 0。我该怎么做?

Edit: My question is how do I move any one of these elements to the beginning? How would I move green to index 0, or blue to index 0? This question is not exclusively about moving the last element to the beginning.

编辑:我的问题是如何将这些元素中的任何一个移到开头?我如何将绿色移动到索引 0,或蓝色移动到索引 0?这个问题不仅仅关于将最后一个元素移到开头。

回答by SharpC

This seems like the simplest way to me. You can move any position to the beginning, not just the last (in this example it moves blue to the beginning).

这对我来说似乎是最简单的方法。您可以将任何位置移动到开头,而不仅仅是最后一个(在本例中,它会将蓝色移动到开头)。

$colours = array("red", "green", "blue", "yellow");

$movecolour = $colours[2];
unset($colours[2]);
array_unshift($colours, $movecolour);

回答by Peter Bailey

Probably the most straightforward way

可能是最直接的方法

array_unshift( $arr, array_pop( $arr ) );

EDIT

编辑

Per your comment "how can I take any one subscript from the array and move it to the beginning", my answer above doesn't fully satisfy that request - it onlyworks by moving the last element to the 0 index.

根据您的评论“我如何从数组中取出任何一个下标并将其移动到开头”,我上面的回答并不能完全满足该请求 - 它只能通过将最后一个元素移动到 0 索引来工作。

This function, however, does satisfy that request

然而,这个功能确实满足了这个要求

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

And, in usage

并且,在使用中

$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

回答by Dereleased

This function will allow you to move an element to an arbitrary position within the array, while leaving the rest of the array untouched:

此函数将允许您将元素移动到数组中的任意位置,同时保持数组的其余部分不变:

function array_reorder($array, $oldIndex, $newIndex) {
    array_splice(
        $array,
        $newIndex,
        count($array),
        array_merge(
            array_splice($array, $oldIndex, 1),
            array_slice($array, $newIndex, count($array))
        )
    );
    return $array;
}

Hopefully the usage is fairly obvious, so this:

希望用法是相当明显的,所以这个:

$array = array('red','green','blue','yellow',);

var_dump(
    array_reorder($array, 3, 0),
    array_reorder($array, 0, 3),
    array_reorder($array, 1, 3),
    array_reorder($array, 2, 0)
);

Will output this:

将输出这个:

array(4) {
  [0]=>
  string(6) "yellow"
  [1]=>
  string(3) "red"
  [2]=>
  string(5) "green"
  [3]=>
  string(4) "blue"
}
array(4) {
  [0]=>
  string(5) "green"
  [1]=>
  string(4) "blue"
  [2]=>
  string(6) "yellow"
  [3]=>
  string(3) "red"
}
array(4) {
  [0]=>
  string(3) "red"
  [1]=>
  string(4) "blue"
  [2]=>
  string(6) "yellow"
  [3]=>
  string(5) "green"
}
array(4) {
  [0]=>
  string(4) "blue"
  [1]=>
  string(3) "red"
  [2]=>
  string(5) "green"
  [3]=>
  string(6) "yellow"
}

回答by dstonek

You want to move one of the elements to the beginning. Let's say

您想将其中一个元素移动到开头。让我们说

$old = array(
'key1' =>'value1', 
'key2' =>'value2', 
'key3' =>'value3', 
'key4' =>'value4');

And you want to move key3 to the beginnig.

并且您想将 key3 移动到 beginnig。

$new = array();
$new['key3'] = $old['key3']; // This is the first item of array $new
foreach($old as $key => $value) // This will continue adding $old values but key3
{
if($key != 'key3')$new[$key]=$value;
}

回答by James Alday

This is very similar to SharpC's answer but accounts for the fact that you may not know where the value is in the array (it's key) or if it is even set. The 'if' check will skip over it if the color isn't set or if it's already the first element in the array.

这与 SharpC 的答案非常相似,但说明了这样一个事实:您可能不知道该值在数组中的位置(它是键),或者甚至不知道它是否已设置。如果未设置颜色或者它已经是数组中的第一个元素,则“if”检查将跳过它。

$color = 'yellow';
$color_array = array("red", "green", "blue", "yellow");

$key = array_search($color, $color_array);

if ($key > 0) {
   unset($color_array[$key]);
   array_unshift($color_array, $color);
}

回答by James

EDITED

已编辑

This is an update based on the question and liking the generic aspects of the answer by Peter Bailey. However, the code is too function/memory intensive for me so below just does a simple swap of the $from and $to values. This method does not cause the array in question to be resized at all, it simply swaps to values within it.

这是基于问题和喜欢 Peter Bailey 回答的一般方面的更新。但是,该代码对我来说太是函数/内存密集型,所以下面只是简单地交换 $from 和 $to 值。此方法根本不会导致有问题的数组调整大小,它只是交换到其中的值。

Second Edit: I added in some more argument checking as mentioned in the comments.

第二次编辑:如评论中所述,我添加了更多参数检查。

function moveValueByIndex( array $array, $from=null, $to=null )
{
  // There is no array, or there are either none or a single entry
  if ( null === $array || count($array) < 2 )
  {
    // Nothing to do, just return what we had
    return $array;
  }

  if ( null === $from )
  {
    $from = count( $array ) - 1;
  }

  if ( null === $to )
  {
    $to = 0;
  }

  if ( $to == $from )
  {
    return $array;
  }

  if ( !array_key_exists($from, $array) )
  {
    throw new Exception( "Key $from does not exist in supplied array." );
  }

  $value = $array[$from];
  $array[$from] = $array[$to];
  $array[$to] = $value;

  return $array;
}

Forgive me if I should have just added this in a comment to Peter's post.. it just was too long to inline all of this there :/

如果我应该在对 Peter 的帖子的评论中添加这个,请原谅我......在那里内嵌所有这些内容太长了:/

回答by ceejayoz

$array = array(
  'red',
  'green',
  'blue',
  'yellow',
);

$last = array_pop($array);
array_unshift($array, $last);

回答by Cups

$a = array('red','green', 'blue','yellow');

$b = array_reverse( $a );

If your question is how to make the last become the first.

如果你的问题是如何让最后一个变成第一个。

回答by Sarfraz

You can do like this:

你可以这样做:

$array = array("red", "green", "blue", "yellow");
$last = array_pop($array);
array_unshift($array, $last);
print_r($array);

Result:

结果:

Array ( [0] => yellow [1] => red [2] => green [3] => blue ) 

回答by dylan maxey

If you aren't always planning on bringing the very last object to the beginning of the array, this would be the most simplistic way to go about it...

如果您不总是计划将最后一个对象带到数组的开头,这将是最简单的方法......

$array = array('red','green','blue','yellow');
unset($array[array_search($searchValue, $array)]);
array_unshift($array, $searchValue);