Consider following list:
请考虑以下列表:
$list = array(
0 => A,
1 => X,
2 => B,
3 => Z,
4 => K,
5 => M
);
I want to change position of A from 0 to 2 then the $list became:
我想将A的位置从0更改为2,然后$ list变为:
$list = array(
0 => X,
1 => B,
2 => A,
3 => Z,
4 => K,
5 => M
);
The following code is what I have tried so far, is there another way using array functions? or any shorter way?
<?php
$list = array(0 => 'A', 1 => 'X', 2 => 'B', 3 => 'Z', 4 => 'K', 5 => 'M');
function change_position($oldposition, $newposition, $list){
echo "Changing $oldposition to $newposition :\n";
foreach($list as $k => $v){
if($oldposition < $newposition){
if( $k < $oldposition ){
$newlist[$k] = $list[$k];
}
if($k >= $oldposition && $k < $newposition){
$newlist[$k] = $list[$k+1];
}
if($k == $newposition){
$newlist[$k] = $list[$oldposition];
}
if($k > $newposition){
$newlist[$k] = $list[$k];
}
}
if($oldposition > $newposition){
if( $k > $oldposition ){
$newlist[$k] = $list[$k];
}
if($k <= $oldposition && $k > $newposition){
$newlist[$k] = $list[$k-1];
}
if($k == $newposition){
$newlist[$k] = $list[$oldposition];
}
if($k < $newposition){
$newlist[$k] = $list[$k];
}
}
}
return $newlist;
}
echo '<pre>';
print_r($list);
print_r(change_position(5, 0, $list));
print_r(change_position(0, 5, $list));
?>
Output:
Array
(
[0] => A
[1] => X
[2] => B
[3] => Z
[4] => K
[5] => M
)
Changing 5 to 0 :
Array
(
[0] => M
[1] => A
[2] => X
[3] => B
[4] => Z
[5] => K
)
Changing 0 to 5 :
Array
(
[0] => X
[1] => B
[2] => Z
[3] => K
[4] => M
[5] => A
)
1 个解决方案
#1
2
Just use array_splice
:
只需使用array_splice:
function move_element(&$array, $element, $position)
{
$key = array_search($element, $array, true);
if ($key === false) {
return;
}
array_splice($array, array_search($key, array_keys($array)), 1);
array_splice($array, $position, 0, $element);
}
Your example would be achieved with
你的例子将通过实现
move_element($list, 'A', 2);
If you don't want to specify the target as a value but as a position it's even easier:
如果您不想将目标指定为值,而是将其指定为位置,则更容易:
function move_element(&$array, $from, $to)
{
$removed = array_splice($array, $from, 1);
array_splice($array, $to, 0, $removed);
}
move_element($list, 0, 2);
#1
2
Just use array_splice
:
只需使用array_splice:
function move_element(&$array, $element, $position)
{
$key = array_search($element, $array, true);
if ($key === false) {
return;
}
array_splice($array, array_search($key, array_keys($array)), 1);
array_splice($array, $position, 0, $element);
}
Your example would be achieved with
你的例子将通过实现
move_element($list, 'A', 2);
If you don't want to specify the target as a value but as a position it's even easier:
如果您不想将目标指定为值,而是将其指定为位置,则更容易:
function move_element(&$array, $from, $to)
{
$removed = array_splice($array, $from, 1);
array_splice($array, $to, 0, $removed);
}
move_element($list, 0, 2);