排序[键=>[值]由另一个具有相同索引的键数组组成 [英] Sort [key => value] array by another array of keys with same index

查看:51
本文介绍了排序[键=>[值]由另一个具有相同索引的键数组组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要对其他数组排序的索引数组:

I have an array of indexes that I want to sort my other array:

$order = [7, 2, 1, 4];

$array = [
   1 => "O",
   2 => "T"
   4 => "F"
   7 => "S"
]

如何基于 $ order 数组对 $ array 进行排序,以便输出是..

How can I order the $array based on $order array, so that the output is..

$array = [
   7 => "S",
   2 => "T"
   1 => "O",
   4 => "F"
]

据我所读,除了for循环外,其他东西都是更可取的

推荐答案

您可以使用 uksort array_search :

You could make use of uksort and array_search:

uksort($array, static function (int $key1, int $key2) use ($order): int {
    return array_search($key1, $order, true) <=> array_search($key2, $order, true);
});

想法是根据数组在 $ order 数组中的项的键的位置对数组进行排序:

The idea is to sort the array by the positions of its items' keys within the $order array:

  • uksort 是一种排序功能,可基于数组键(此处为1、2、4和7)进行排序,
  • array_search($ key1,$ order,true)为您提供 $ key1 $ order
  • 中的位置
  • array_search($ key2,$ order,true)为您提供 $ key2 $ order
  • 中的位置
  • < => (称为
  • uksort is a sorting function that allows sorting based on array keys (here 1, 2, 4 and 7),
  • array_search($key1, $order, true) gives you $key1's position within $order,
  • array_search($key2, $order, true) gives you $key2's position within $order,
  • <=> (known as the spaceship operator) compares these values, so that the sorting puts lower values (aka lower positions within $order) first.

> 演示

注意:如果数组很大,性能可能会很差,因为 array_search 将在同一键上运行多次.如果这是一个问题,您可以做的是先获取 $ order 中所有键的位置,然后根据它们进行排序.

Note: performance could be bad if your array is big, as array_search will be run several times on the same keys. If that's an issue, what you can do is grab all keys' positions within $order first, then sort based on them.

这篇关于排序[键=>[值]由另一个具有相同索引的键数组组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆