douju8113 2014-07-29 14:10
浏览 112
已采纳

PHP按另一个数组(表)按键对数组进行排序

I have an array as table:

$sortLikeThis = [
    '5',
    '3',
    '7'
    '1',
];

$unsorted = [
    [
        'sort' => '7',
        'name' => 'Test',
    ],
    [
        'sort' => '1',
        'name' => 'Test 2',
    ],
    [
        'sort' => '3',
        'name' => 'Test 3',
    ],
    [
        'sort' => '5',
        'name' => 'Test 4',
    ],
    [
        'sort' => '7',
        'name' => 'Test 4',
    ],
]

I want to get sortered array ($unsorted) by sort key like in $sortLikeThis.

e.g.:

$output = [
    [
        'sort' => '5',
        'name' => 'Test 4',
    ],
    [
        'sort' => '3',
        'name' => 'Test 3',
    ],
    [
        'sort' => '7',
        'name' => 'Test',
    ],
    [
        'sort' => '7',
        'name' => 'Test 4',
    ],
    [
        'sort' => '1',
        'name' => 'Test 2',
    ],
]

What should I use?

  • 写回答

1条回答 默认 最新

  • dqppv86022 2014-07-29 14:16
    关注

    Just use usort():

    usort($unsorted, function($x, $y) use ($sortLikeThis)
    {
       return array_search($x['sort'], $sortLikeThis) - array_search($y['sort'], $sortLikeThis);
    });
    

    Check the fiddle.

    Hint: with current structure, you'll trigger array_search() (linear time) for each element, which may be slow. Thus, it can be optimized:

    $sortLikeThis = array_flip($sortLikeThis);
    
    usort($unsorted, function($x, $y) use ($sortLikeThis)
    {
       return $sortLikeThis[$x['sort']] - $sortLikeThis[$y['sort']];
    });
    

    With this each lookup will be O(1) since it's a hash-table search.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突