将数组元素移动到 PHP 中的新索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12624153/
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
Move an array element to a new index in PHP
提问by cronoklee
I'm looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt need to work with associative arrays. Anyone got ideas for this one?
我正在寻找一个简单的函数来将数组元素移动到数组中的新位置并对索引重新排序,以便序列中没有间隙。它不需要使用关联数组。有人对这个有想法吗?
$a = array(
0 => 'a',
1 => 'c',
2 => 'd',
3 => 'b',
4 => 'e',
);
print_r(moveElement(3,1))
//should output
[ 0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e' ]
回答by hakre
As commented, 2x array_splice, there even is no need to renumber:
正如评论的 2x array_splice,甚至不需要重新编号:
$array = [
0 => 'a',
1 => 'c',
2 => 'd',
3 => 'b',
4 => 'e',
];
function moveElement(&$array, $a, $b) {
$out = array_splice($array, $a, 1);
array_splice($array, $b, 0, $out);
}
moveElement($array, 3, 1);
Result:
结果:
[
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd',
4 => 'e',
];
回答by RubbelDeCatc
The solution from hakre with two array_splice commands doesn't work with named arrays. The key of the moved element will be lost.
来自 hakre 的带有两个 array_splice 命令的解决方案不适用于命名数组。被移动元素的键将丢失。
Instead you can splice the array two times and merge the parts.
相反,您可以将数组拼接两次并合并各个部分。
function moveElement(&$array, $a, $b) {
$p1 = array_splice($array, $a, 1);
$p2 = array_splice($array, 0, $b);
$array = array_merge($p2,$p1,$array);
}
How does it work:
它是如何工作的:
- First: remove/splice the element from the array
- Second: splice the array into two parts at the position you want to insert the element
- Merge the three parts together
- 第一:从数组中移除/拼接元素
- 第二:在你要插入元素的位置将数组拼接成两部分
- 将三个部分合并在一起
Example:
例子:
$fruits = array(
'bananas'=>'12',
'apples'=>'23',
'tomatoes'=>'21',
'nuts'=>'22',
'foo'=>'a',
'bar'=>'b'
);
moveElement($fruits, 1, 3);
// Result
['bananas'=>'12', 'tomatoes'=>'21', 'nuts'=>'22', 'apples'=>'23', 'foo'=>'a', 'bar'=>'b']
回答by Samy Arous
Arrays in PHP are not actual array in the C sens but associative arrays. But the way to move a value from an index to another is quiet straight forward and is the same as in C++:
PHP 中的数组不是 C sens 中的实际数组,而是关联数组。但是将一个值从一个索引移动到另一个索引的方法很简单,并且与 C++ 中的相同:
Copy the value to move to a temporary buffer, translate all the elements to crush the empty spot at the source position and in the same free up a spot on the destination position. Put the backup value in the destination spot.
复制要移动到临时缓冲区的值,转换所有元素以压碎源位置的空白点,同时释放目标位置的一个点。将备份值放在目标位置。
function moveElement ($a , $i , $j)
{
$tmp = $a[$i];
if ($i > $j)
{
for ($k = $i; $k > $j; $k--) {
$a[$k] = $a[$k-1];
}
}
else
{
for ($k = $i; $k < $j; $k++) {
$a[$k] = $a[$k+1];
}
}
$a[$j] = $tmp;
return $a;
}
$a = array(0, 1, 2, 3, 4, 5);
print_r($a);
$a = moveElement($a, 1, 4);
echo ('1 -> 4');
print_r($a);
$a = moveElement($a, 5, 0);
echo ('5 -> 0' );
print_r($a);
Output:
输出:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
1 -> 4Array
(
[0] => 0
[1] => 2
[2] => 3
[3] => 4
[4] => 1
[5] => 5
)
5 -> 0Array
(
[0] => 5
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 1
)
You'll need to add some Exception handling to have a complete code.
您需要添加一些异常处理以获得完整的代码。
回答by Dabi
A function that preserves keys:
保留键的函数:
function moveElementInArray($array, $toMove, $targetIndex) {
if (is_int($toMove)) {
$tmp = array_splice($array, $toMove, 1);
array_splice($array, $targetIndex, 0, $tmp);
$output = $array;
}
elseif (is_string($toMove)) {
$indexToMove = array_search($toMove, array_keys($array));
$itemToMove = $array[$toMove];
array_splice($array, $indexToMove, 1);
$i = 0;
$output = Array();
foreach($array as $key => $item) {
if ($i == $targetIndex) {
$output[$toMove] = $itemToMove;
}
$output[$key] = $item;
$i++;
}
}
return $output;
}
$arr1 = Array('a', 'b', 'c', 'd', 'e');
$arr2 = Array('A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e');
print_r(moveElementInArray($arr1, 3, 1));
print_r(moveElementInArray($arr2, 'D', 1));
Ouput:
输出:
Array
(
[0] => a
[1] => d
[2] => b
[3] => c
[4] => e
)
Array
(
[A] => a
[D] => d
[B] => b
[C] => c
[E] => e
)
回答by ruidovisual
May be I'm wrong but shouldn't it be easier just to make a copy of the array and then replace the values?
可能是我错了,但只是制作数组的副本然后替换值不应该更容易吗?
function swap($input, $a, $b){
$output = $input;
$output[$a] = $input[$b];
$output[$b] = $input[$a];
return $output;
}
$array = ['a', 'c', 'b'];
$array = swap($array, 1, 2);
回答by Aksen P
Based on a previous answer. In case if you need to save key indexes of an associative array, which are could be any number or string:
基于之前的回答。如果您需要保存关联数组的键索引,可以是任何数字或字符串:
function custom_splice(&$ar, $a, $b){
$out = array_splice($ar, $a, 1);
array_splice($ar, $b, 0, $out);
}
function moveElement(&$array, $a, $b) {
$keys = array_keys($array);
custom_splice($array, $a, $b);
custom_splice($keys, $a, $b);
$array = array_combine($keys,$array);
}
$s = '{
"21": "b",
"2": "2",
"3": "3",
"4": "4",
"6": "5",
"7": "6"
}';
$e = json_decode($s,true);
moveElement($e, 2, 0);
print_r($e);
Array
(
[3] => 3
[21] => b
[2] => 2
[4] => 4
[6] => 5
[7] => 6
)
A previous answerdestroys numeric indexes - makes them start from 0.
A previous answer销毁数字索引 - 使它们从0.
回答by athre0z
Take a look at thisthread which describes a similar problem. The following solution is provided:
看看这个线程,它描述了一个类似的问题。提供了以下解决方案:
/**
* 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;
}
回答by Francisco Presencia
You need to create an auxiliary variable.
您需要创建一个辅助变量。
moveElement($a, $i,$j)
{
$k=$a[$i];
$a[$i]=$a[$j];
$a[$j]=$k;
return $a;
}

