本文介绍了在PHP中使用“自定义键"对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的结构数组

I have an array of one structure like below

$array1 = array(
[123] => array('1'=>'1','2'=>'3'),
[345] => array('1'=>'3','2'=>'5'),
[789] => array('1'=>'1','2'=>'5'),
[567] => array('1'=>'6','2'=>'5'),
);

和另一个数组结构,如 $ array2 = array(567,345,789,123);

and another array structure as $array2 = array(567,345,789,123);

现在我想用php sort函数对这个数组进行排序,我的意思是用第二个数组对第一个数组进行排序,使其看起来像所需的输出,例如下方

Now i want to sort this one with php sort function, i mean sort the first array with second one to looks like the desired output something likebelow

$array1 = array(
[567] => array('1'=>'6','2'=>'5'),
[345] => array('1'=>'3','2'=>'5'),
[789] => array('1'=>'1','2'=>'5'),
[123] => array('1'=>'1','2'=>'3'),
);

我想使用任何已经存在的排序功能来获得这些期望的结果.

I want to get these desired result with any sorting function which is already exists.

谢谢.

推荐答案

环绕您的 $ array2 并填充第三个数组,如下所示:

Loop your $array2 and populate a third array as follows:

$array1 = array(
    [123] => array('1'=>'1','2'=>'3'),
    [345] => array('1'=>'3','2'=>'5'),
    [789] => array('1'=>'1','2'=>'5'),
    [567] => array('1'=>'6','2'=>'5'),
);

$array2 = array(567,345,789,123);

$orderedArray = array();
foreach ($array2 as $key) {
    $orderedArray[$key] = $array1[$key];
}

如果需要功能:

function orderArray($arrayToOrder, $keys) {
    $ordered = array();
    foreach ($keys as $key) {
        if (isset($arrayToOrder[$key])) {
             $ordered[$key] = $arrayToOrder[$key];
        }
    }
    return $ordered;
}

$myOrderedArray = orderArray($array1, $array2);

这篇关于在PHP中使用“自定义键"对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:47