按其他数组值排序数组键和值

时间:2017-05-23 09:45:15

标签: php arrays sorting

我有两个阵列,需要按另一个排序。

包含订单的数组的类别为值:

$order = array(
      0 => 12,
      1 => 14,
      2 => 15,
      3 => 17,
      4 => 20
      ); 

我需要排序的数组有唯一的ID作为键,类别有值,类别有重复:

$array = array(
     432 => 20,
     433 => 20,
     235 => 15,
     543 => 17,
     564 => 17,
     879 => 14,
     125 => 12,
     987 => 12,
     453 => 20
);

我需要的是一个数组,其中排序的ID为键或值(首选):

// sorted as keys
$sorted = array(
    125 => 12,
    987 => 12,
    879 => 14,
    235 => 15,
    543 => 17,
    564 => 17,
    432 => 20,
    433 => 20,
    453 => 20 
);


// or sorted as values
$sorted = array(
    0 => 125,
    1 => 987,
    2 => 879,
    3 => 235,
    4 => 543,
    5 => 564,
    6 => 432,
    7 => 433,
    8 => 453
);

2 个答案:

答案 0 :(得分:0)

首先排序数组键升序,然后根据$order数组执行uasort

ksort($array);
uasort($array, function($a, $b) use ($order) {
    return (array_search($a, $order) < array_search($b, $order)) ? -1 : 1;
});

print '<pre>';
print_r($array);

答案 1 :(得分:-1)

这就是你所拥有的:

$array = array(
 432 => 20,
 433 => 20,
 235 => 15,
 543 => 17,
 564 => 17,
 879 => 14,
 125 => 12,
 987 => 12,
 453 => 20
);

这需要像这样处理:

  1. 要按升序按键排序数组:$sorted = ksort($array);
  2. 要按键降序排序数组:$sorted = krsort($array);