沃梦达 / 编程问答 / php问题 / 正文

PHP - 按另一个数组对多维数组进行排序

PHP - Sort multi-dimensional array by another array(PHP - 按另一个数组对多维数组进行排序)

本文介绍了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.

假设我有这两个数组:

$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 - 按另一个数组对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP - 按另一个数组对多维数组进行排序

基础教程推荐