PHP按键排序关联数组,这些键存在于其他数组中 [英] php sort associative arrays by keys that those keys exist in other array

查看:80
本文介绍了PHP按键排序关联数组,这些键存在于其他数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组

$myArray=array(

'a'=>array('id'=>1,'text'=>'blabla1'),
'b'=>array('id'=>2,'text'=>'blabla2'),
'c'=>array('id'=>3,'text'=>'blabla3'),
'd'=>array('id'=>4,'text'=>'blabla4'),

);

我想通过存在的键a,b,c,d对上述数组进行排序在另一个数组中:

and i want to sort the above array by the keys a,b,c,d, who exist in another array:

$tempArray=array('c','a','d','b');

我该怎么做,这样$ myArray

How can I do that so the $myArray

看起来像这样:

$myArray=array(

'c'=>array('id'=>3,'text'=>'blabla3'),
'a'=>array('id'=>1,'text'=>'blabla1'),
'd'=>array('id'=>4,'text'=>'blabla4'),
'b'=>array('id'=>2,'text'=>'blabla2'),

);

感谢您的帮助!

推荐答案

最简单且可能最有效的方法是通过迭代保存排序顺序的数组并创建一个新的已排序数组:

The simplest and likely most efficient way to do this is by iterating the array that holds the sort order and creating a new, sorted array:

$sorted = array();

foreach ($tempArray as $order) {
  if (isset($myArray[$order])) {
    $sorted[$order] = $myArray[$order];
  }
}

print_r($sorted);

之所以有效,是因为关联数组隐式具有将元素添加到数组中的顺序。

This works because associative arrays implicitly have an order of the order in which elements were added to the array.

看到它正常工作

EDIT

任何涉及排序功能的解决方案都可能比这效率低得多。这是因为要执行此操作,您将需要使用带有回调的函数-这已经隐含了函数调用的开销。

Any solution involving a sorting function will likely be much less efficient than this. This is because in order to do it you will need to use a function that takes a callback - this already has an implied overhead of the function call.

排序函数通过比较项目来工作,这意味着这些解决方案的复杂性都将大于此解决方案的复杂性(此解决方案的复杂性只是 O(n))。另外,为了获得排序函数的返回值,您需要检查目标数组,找到要比较的每个键的位置,对于每次比较,甚至增加了更多的复杂性。

The sorting functions also work by comparing items, meaning that the complexity any of those solutions will be greater than that of this solution (the complexity of this is simply O(n)). Also, in order to derive the return value for the sorting function you would need to inspect the target array, finding the position of each of the keys being compared, for each comparison, adding even more complexity.

这篇关于PHP按键排序关联数组,这些键存在于其他数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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