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

时间:2014-02-28 13:55:15

标签: 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','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');

请任何想法。

2 个答案:

答案 0 :(得分:1)

这是由用户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中)。

答案 1 :(得分: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));
相关问题