如何通过其他数组键对数组键进行排序?

时间:2013-12-04 11:47:46

标签: php arrays

例如,我有两个数组:

$first_array = array(
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => 'd',
    5 => 'e'
);

$second_array = array(
    1 => 'not important',
    4 => 'not important',
    3 => 'not important',
    5 => 'not important',
    2 => 'not important',
);

是否有任何函数可以按顺序排列第二个数组键的第一个数组键(带值)?或者我只需要循环第二个数组并首先通过键重新创建?

更新 结果值应按秒数组键序列

排列
$result = array(
    1 => 'a',
    2 => 'd',
    3 => 'c',
    4 => 'e',
    5 => 'b'
);

3 个答案:

答案 0 :(得分:0)

同样的问题已经发布

Sort array by keys of another array

Sort an Array by keys based on another Array?

希望会有所帮助!

答案 1 :(得分:0)

你可以这样做......

<?php
$first_array = array(
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => 'd',
    5 => 'e'
);

$second_array = array(
    1 => 'not important',
    4 => 'not important',
    3 => 'not important',
    5 => 'not important',
    2 => 'not important',
);


foreach($first_array as $k=>$v)
{
$second_array[$k]=$v;
}

$result = array_values($second_array);
array_unshift($result, "dummy");
unset($result[0]);
print_r($result);

<强>输出:

Array
(
    [1] => a
    [2] => d
    [3] => c
    [4] => e
    [5] => b
)

答案 2 :(得分:0)

你可以通过使用单个foreach()循环和array_flip()来实现;和array_combine();

     $f = array(
    1 => 'a',
    2 => 'b',
    3 => 'c',
    4 => 'd',
    5 => 'e'
);
$s = array(
    1 => 'dummy',
    4 => 'dummy',
    3 => 'dummy',
    5 => 'dummy',
    2 => 'dummy',
);
$c=array();
$j=1;
foreach($s as $k=>$v){

$c[]=$f[$k];

}
$f=array_flip($f);
$c=array_combine($f,$c);

print_r($c);