数组排序由另一个数组的钥匙 [英] Sort array by keys of another array

查看:166
本文介绍了数组排序由另一个数组的钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有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);

这篇关于数组排序由另一个数组的钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆