PHP重新排序数字索引数组

时间:2016-01-14 16:52:14

标签: php arrays sorting

我需要任意重新排序数字索引数组。采用以下数组表示文档中的页面:

$array[0  => 0
       1  => 1,
       2  => 2,
       3  => 3,
       4  => 4,
       5  => 5,
       6  => 6,
       7  => 7,
       8  => 8,
       9  => 9,
       10 => 10 ];

第二个数组定义了特定元素的新顺序(同时自动重新排序那些与之相冲突的元素):

$reordered[3 => 4,
           7 => 9,
           6 => 1 ];

我需要一个看起来像这样的结果数组:

$array[0  => 0
       1  => 2,
       2  => 3,
       3  => 4,
       4  => 5,
       5  => 6,
       6  => 1,
       7  => 9,
       8  => 7,
       9  => 8,
       10 => 10 ];

注意元素被替换的位置,其他元素被重新编入索引(同时尊重$ reordered数组的配置)。

实现这一目标最优雅的方法是什么?

3 个答案:

答案 0 :(得分:0)

以下代码完成了这项工作:

asort($reordered);
foreach ($reordered as $position => $item) {
    $sliced = array_splice($array, array_search($item, $array), 1);
    array_splice($array, $position, 0, $sliced);
}
print_r($array);

输出:

Array
(
    [0] => 0
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 1
    [7] => 9
    [8] => 7
    [9] => 8
    [10] => 10
)

或者您可以使用reorder中的Nspl功能。它有以下签名:

reorder(array $list, $from, $to)

解决方案将是:

use function nspl\a\reorder;

asort($reordered);
foreach ($reordered as $position => $item) {
    $array = reorder($array, array_search($item, $array), $position);
}

答案 1 :(得分:0)

试试这个:最好的方法。我希望我解决了你的问题。使用array_search($ 2,$ array);给2.找到并索引以替换下面给出的值。

<?php
$array=array(0=>0,1=>1,2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9);
$r=array(4=>2,5=>4,3=>6);
print_r($array);
echo "<br>";
$count=count($array);
foreach($r as $key =>$val){
$a=$array[$key];
$keyu = array_search($val, $array);
$array[$keyu]=$a;
$array[$key]=$val;
}
print_r($array);
?>

结果:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 )
Array ( [0] => 0 [1] => 1 [2] => 5 [3] => 6 [4] => 2 [5] => 4 [6] => 3 [7] => 7 [8] => 8 [9] => 9 ) 

答案 2 :(得分:0)

正常工作试试这个:

$old = range(100,110);
$order = array(3=>4,6=>1,7=>9);

function match($old,$order){
    foreach ($old as $k => $v){
        if(array_key_exists($k, $order)){
            $new[] = $order[$k];
        }else{
            $new[] = $v;
        }
    }
    return $new;
}
echo "<pre>";
print_r($old);
print_r($order);
print_r(match($old,$order));

输出:

Array
(
    [0] => 100
    [1] => 101
    [2] => 102
    [3] => 103
    [4] => 104
    [5] => 105
    [6] => 106
    [7] => 107
    [8] => 108
    [9] => 109
    [10] => 110
)
Array
(
    [3] => 4
    [6] => 1
    [7] => 9
)
Array
(
    [0] => 100
    [1] => 101
    [2] => 102
    [3] => 4
    [4] => 104
    [5] => 105
    [6] => 1
    [7] => 9
    [8] => 108
    [9] => 109
    [10] => 110
)