PHP-用另一个数组对多维数组进行排序 [英] PHP - Sort multi-dimensional array by another array

查看:77
本文介绍了PHP-用另一个数组对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按另一个数组对多维数组进行排序,但到目前为止还很短.
array_multisort 似乎仅适用于实际排序.

I'm trying to sort a multi-dimensional array by another array, but have so far come up short.
array_multisort seems be working only for real sorting.

假设我有以下两个数组:

Suppose I have these 2 arrays:

$order = array(2,3,1);

$data = array(
    array('id' => 1, 'title' => 'whatever'),
    array('id' => 2, 'title' => 'whatever'),
    array('id' => 3, 'title' => 'whatever')
);

现在我想根据$order数组中的顺序对$data数组进行排序.
这就是我想要的结果:

Now I would like to sort my $data array according to the order in my $order array.
This is what I would like the result to be:

$data = array(
    array('id' => 2, 'title' => 'whatever'),
    array('id' => 3, 'title' => 'whatever')
    array('id' => 1, 'title' => 'whatever'),
);


我可以通过运行嵌套循环轻松完成此操作,但是伸缩性不好(我的数组很大,并且数组具有更多字段).


I can accomplish this easily by running a nested loop, but that would not scale well (my array is pretty big, and the arrays have many more fields).

推荐答案

PHP中没有为此内置的函数,我无法想到任何自定义函数,可以使用usort做到这一点.但是 array_map 很简单,imo,那么为什么不使用它呢?

There is no built-in function for this in PHP and i am unable to think of any custom function, which would do this using usort. But array_map is simple enough, imo, so why not use it instead?

$sorted = array_map(function($v) use ($data) {
    return $data[$v - 1];
}, $order);

这篇关于PHP-用另一个数组对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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