楼上的答案都是正确的 ... 不过不够帅 ... 我画蛇添足一下好了 ...
如果原数组的键值不是数字而是字符串的话 ... 这样的排序可以一行解决 ...<?php
/* the original array with string keys ... */
$src = [
'a' => 'foo',
'b' => 'bar',
'c' => 'baz',
];
/* the order array ... */
$order = [ 'b', 'a', 'c' ];
/* sort using single line ... */
print_r( array_merge( array_flip( $order ), $src ) );
但是 array_merge() 这个函数有个倒霉特性 ...
当原数组的键值整形化之后不为零的时候 ... 不论原来的键值是什么顺序都会被这个函数全部丢弃 ...
所以你的需求没办法用这种简单的方式解决 ... 只能借助于排序函数 ... 代码如下 ...<?php
/* the original array with integer keys ... */
$src = [
'1' => 'foo',
'2' => 'bar',
'3' => 'baz',
];
/* the order array ... type is not important ... */
$order = [ 1, '3', 0b10 ];
/* get order weight ... */
$weight = array_flip( $order );
/* we do not want to change the source array order huh ..? */
$dst = $src;
/* 3 lines sorting ... not very difficult ... */
uksort( $dst, function( $left, $right ) use ( $weight ) {
/* $left never equals to $right ... so 0 is impossible ... */
return ( $weight[$left] < $weight[$right] ) ? -1 : 1;
} );
/* show time ... */
print_r( $dst );
这种方式虽然写起来复杂 ... 但时间复杂度要低于楼上的整个遍历重生成新数组 ...
所以效率更高 ... 并且如果需要更改排序方式的话也更加灵活 ...
恩 ... 就是这样啦 ...