将具有特定键的数组项移动到数组中的第一个位置,PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11703729/
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 array item with certain key to the first position in an array, PHP
提问by user965748
What's the most elegant way in PHP to move an array element chosen by key to the first position?
PHP 中将键选择的数组元素移动到第一个位置的最优雅方式是什么?
Input:
输入:
$arr[0]=0;
$arr[1]=1;
$arr[2]=2;
....
$arr[n]=n;
$key=10;
Output:
输出:
$arr[0]=10;
$arr[1]=0;
$arr[2]=1;
$arr[3]=2;
....
$arr[n]=n;
采纳答案by wp student
回答by Yan Berk
Use array_unshift:
$new_value = $arr[n];
unset($arr[n]);
array_unshift($arr, $new_value);
回答by Justin
Old question, and already answered, but if you have an associative array you can use array_merge.
老问题,已经回答,但如果你有一个关联数组,你可以使用 array_merge。
$arr = array_merge([$key=>$arr[$key]], $arr);
EDITED (above to show PHP7+ notation, below is example)
已编辑(上面显示 PHP7+ 符号,下面是示例)
$arr = ["a"=>"a", "b"=>"b", "c"=>"c", "d"=>"d"];
$arr = array_merge(["c"=>$arr["c"]], $arr);
The effective outcome of this operation
本次操作的有效结果
$arr == ["c"=>"c", "a"=>"a", "b"=>"b", "d"=>"d"]
回答by leejmurphy
Something like this should work. Check if the array key exists, get its value, then unsetit, then use array_unshiftto create the item again and place it at the beginning.
像这样的事情应该有效。检查数组键是否存在,获取它的值,然后获取unset它,然后使用array_unshift它再次创建该项目并将其放在开头。
if(in_array($key, $arr)) {
$value = $arr[$key];
unset($arr[$key]);
array_unshift($arr, $value);
}
回答by Opi
<?php
$key = 10;
$arr = array(0,1,2,3);
array_unshift($arr,$key);
var_dump($arr) //10,0,1,2,3
?>
回答by Cups
$arr[0]=0;
$arr[1]=1;
$arr[2]=2;
$arr[3]=10;
$tgt = 10;
$key = array_search($tgt, $arr);
unset($arr[$key]);
array_unshift($arr, $tgt);
// var_dump( $arr );
array
0 => int 10
1 => int 0
2 => int 1
3 => int 2
回答by Veve
Since any numeric key would be re-indexed with array_unshift(as noted in the doc), it's better to use the +array union operator to move an item with a certain key at the first position of an array:
由于任何数字键都将被重新索引array_unshift(如doc 中所述),最好使用+数组联合运算符在数组的第一个位置移动具有特定键的项目:
$item = $arr[$key];
unset($arr[$key]);
$arr = array($key => $item) + $arr;
回答by Shashank Srivastava
$tgt = 10;
$key = array_search($tgt, $arr);
for($i=0;$i<$key;$i++)
{
$temp = $arr[$i];
$arr[$i] = $tgt;
$tgt = $temp;
}
After this simple code, all you need to do is display the re-arranged array. :)
在这段简单的代码之后,您需要做的就是显示重新排列的数组。:)

