数组排序由另一个数组的钥匙
问题描述:
有2阵列,都具有相同的长度和相同的键:
There are 2 arrays, both with the same length and with the same keys:
$a1 = [1=>2000,65=>1354,103=>1787];
$a2 = [1=>'hello',65=>'hi',103=>'goodevening'];
asort($a1);
的A1和A2键的ID从数据库中。
The keys of a1 and a2 are id's from a database.
A1得到由值排序。一旦排序,我们如何可以使用相同的排序顺序在A2?
a1 gets sorted by value. Once sorted, how can we use the same sorting order in a2?
谢谢!
答
我相信这个作品:
$a1 = array(1=>2000,65=>1354,103=>1787);
$a2 = array(1=>'hello',65=>'hi',103=>'goodevening');
asort($a1); // sort $a1, maintaining array index
// sort $a2 by key, using the order of $a1
function my_uksort($a, $b) {
global $a1;
return $a1[$a] < $a1[$b] ? -1 : 1;
}
uksort($a2, 'my_uksort');
var_dump($a1);
var_dump($a2);