如何根据另一个数组对一个数组进行排序?

时间:2015-06-10 19:49:05

标签: php arrays sorting multidimensional-array

我有一个存储在数组中的两个数组。它们具有相同数量的值并且是对齐的:

$matrix['label1']
$matrix['label2']

我想对$ matrix ['label1']应用字母排序,并以相同的模式移动$ matrix ['label1']的内容。以下是输入和输出的示例。

$matrix['label1'] = ['b','c','a']
$matrix['label2'] = [ 1, 2, 3]

asort($matrix['label1'])
// outputs ['a','b','c']
//$matrix['label2'] should now be depending on that [ 3, 1, 2] 

如何更改asort()电话以使其正常工作?

1 个答案:

答案 0 :(得分:4)

您正在寻找array_multisort(),只需将两个subArrays作为参数传递给它:

<?php

    $matrix['label1'] = ['b','c','a'];
    $matrix['label2'] = [ 1, 2, 3];

    array_multisort($matrix['label1'], $matrix['label2']);
    print_r($matrix);

?>

输出:

Array
(
    [label1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [label2] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 2
        )

)