Php 按值更改数组索引并重新排序

Php 按值更改数组索引并重新排序,php,arrays,sorting,Php,Arrays,Sorting,我有一系列的值,比如 $array = array(1,2,3,4); 我希望能够重新定位元素并重新排序。 编辑:要明确这一点,我不只是想随意移动元素,我想将一个元素移动到数组中的新位置,并保持其他元素的顺序。 比如, // move value 3 to index[1], result $array(1,3,2,4); // or move value 1 to index[3], result $array[2,3,4,1); 如有需要,使其更清楚 $array('alice','b

我有一系列的值,比如

$array = array(1,2,3,4); 
我希望能够重新定位元素并重新排序。
编辑:要明确这一点,我不只是想随意移动元素,我想将一个元素移动到数组中的新位置,并保持其他元素的顺序。 比如,

// move value 3 to index[1], result
$array(1,3,2,4);
// or move value 1 to index[3], result
$array[2,3,4,1);
如有需要,使其更清楚

$array('alice','bob','colin','dave');
// move value 'colin' to index[1], result
$array('alice','colin','bob','dave');
// or move value 'alice' to index[3], result
$array('bob','colin','dave', 'alice');

请提供任何想法。

这是用户hakre从另一个StackOverflow线程复制的,但此函数应该可以工作:

$array = array(1,2,3,4);
function moveElement(&$array, $a, $b) {
    $out = array_splice($array, $a, 1);
    array_splice($array, $b, 0, $out);
}

moveElement($array, 3, 1); // would move the value of the element at position [3] (the number 4 in the array example) to position [1]
//would output: Array ( [0] => 1 [1] => 4 [2] => 2 [3] => 3 )
它接受$array数组并将元素3重新定位到示例中的[1]位置。使用函数参数将任意元素值(在示例3中)移动到任意位置(在示例1中)。

尝试以下代码:

function swap_value(&$array,$first_index,$last_index){
    $save=$array[$first_index];
    $array[$first_index]=$array[$last_index];
    $array[$last_index]=$save;
    return $array;
}
$array = array(1,2,3,4); 
var_dump(swap_value($array,1,2));
var_dump(swap_value($array,0,2));

对想详细说明您的评论吗?这将导致
1,4,2,3
。谢谢。我编辑我的帖子是为了反映一个“4”,而不是我最初偶然写的“3”。是的,但OP希望2,3,1,4链接到原始源?至少在关联数组上会失败(因为交换值而不是键)。此外,键将保持不变(因此值将被交换,而键将不被交换)@AlmaDo Ok。将函数名更改为
swap_value
:-)只是为了澄清:是否要获取一个值并将其移动到特定索引?@joseftosson,是的。如果可能的话,我想通过它的值来选择要移动的内容。也许你可以通过将示例更改为包含字母而不是数字来更清楚地说明这一点。到目前为止,所有回复都将索引作为参数。并不是说很难找到一个值的索引,但大多数答案都忽略了问题的这一部分。你关心索引的值吗?你只对数字索引感兴趣吗?