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条)

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!