PHP - 根据特定键

时间:2015-12-16 22:00:06

标签: php arrays sorting

我有两个数组需要根据一个特定值反映相同的顺序。我的第一个数组$array1是一系列整数,我需要$array2中的辅助数组,它们具有相同的整数值(以及我剩下的一大堆其他数据)为简洁起见,请重新排序以反映$array1中整数的顺序。

目前我有:

$array1 = array(
   [0] => 19,
   [1] => 15,
   [2] => 18,
   [3] => 20
);

$array2 = array (
   [0] => array (
       [0] => 20,
       [1] => 'Some other data.'
   ),
   [1] => array (
       [0] => 18,
       [1] => 'Some other data.'
   ),
   [2] => array (
       [0] => 19,
       [1] => 'Some other data.'
   ),
   [3] => array (
       [0] => 15,
       [1] => 'Some other data.'
   )
);

期望排序$array2

$array2 = array (
   [0] => array (
       [0] => 19,
       [1] => 'Some other data.'
   ),
   [1] => array (
       [0] => 15,
       [1] => 'Some other data.'
   ),
   [2] => array (
       [0] => 18,
       [1] => 'Some other data.'
   ),
   [3] => array (
       [0] => 20,
       [1] => 'Some other data.'
   )
)

2 个答案:

答案 0 :(得分:0)

在这种情况下,您应该使用uasort()

function cmp($a, $b) {
    $posA = array_search($a[0], $array1);
    $posB = array_search($b[0], $array1);

    if ($posA == $posB) {
        return 0;
    }
    return ($posA < $posB) ? -1 : 1;
}

uasort($array2, 'cmp');

但它会很慢......

答案 1 :(得分:0)

// make order in form "what => place"
$flip = array_flip($array1);

$new = array();
foreach($array2 as $key=>$item) {
   $i = $item[0];
   $new[$flip[$i]] = $item;
}

demo on eval.in