有 2 个数组,长度相同,键也相同:
$a1 = [1=>2000,65=>1354,103=>1787];
$a2 = [1=>'hello',65=>'hi',103=>'goodevening'];
asort($a1);
a1 和 a2 的键是来自数据库的 id。
a1 按值排序。排序后,我们如何在 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);
关于php - 按另一个数组的键对数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2685031/