dongqiang4986 2018-06-22 06:45
浏览 5
已采纳

在PHP中使用另一个数组排序数组的最佳方法是什么?

Suppose I have an array that I want to sort, and the order is not something computable, but rather, given by another array which lists the keys in the desired order:

$ordering_array = [
    'c',
    'a',
    'k',
    'e',
];

As an added complication, not all of these keys might be present in my array to sort:

$given_array = [
    'a' => 'value',
    'c' => 'value',
    'e' => 'value',
];

What is the cleanest / quickest way to achieve this?

My method is:

$new_array = array_fill_keys($ordering_array, NULL);

foreach ($given_array as $key => $value) {
  $new_array[$key] = $value;
}

$new_array = array_filter($new_array);

Is there a better way?

  • 写回答

6条回答 默认 最新

  • dqifn68206 2018-06-22 06:52
    关注

    You can replace the foreach with array_replace()

    $new_array = array_fill_keys($ordering_array, NULL);
    $new_array = array_replace($new_array, $given_array);
    $new_array = array_filter($new_array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?