我正在尝试按另一个数组对多维数组进行排序,但到目前为止还不够.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 - 按另一个数组对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 SELECT(MYSQL/PHP) 中加入 2 个表Joining 2 tables in SELECT(MYSQL/PHP)(在 SELECT(MYSQL/PHP) 中加入 2 个表)
如何使<option selected=“selected">由How to make lt;option selected=quot;selectedquot;gt; set by MySQL and PHP?(如何使lt;option selected=“selectedgt;由 MySQL 和 PHP 设置?)
使用 PHP 中的数组自动填充选择框Auto populate a select box using an array in PHP(使用 PHP 中的数组自动填充选择框)
PHP SQL SELECT where like search item with multiple wordsPHP SQL SELECT where like search item with multiple words(PHP SQL SELECT where like search item with multiple words)
json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT(json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8)
MySQL ORDER BY rand(),名称 ASCMySQL ORDER BY rand(), name ASC(MySQL ORDER BY rand(),名称 ASC)