問題描述
我正在嘗試按另一個(gè)數(shù)組對多維數(shù)組進(jìn)行排序,但到目前為止還不夠.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.
假設(shè)我有這兩個(gè)數(shù)組:
$order = array(2,3,1);
$data = array(
array('id' => 1, 'title' => 'whatever'),
array('id' => 2, 'title' => 'whatever'),
array('id' => 3, 'title' => 'whatever')
);
現(xiàn)在我想根據(jù)我的 $order
數(shù)組中的順序?qū)ξ业?$data
數(shù)組進(jìn)行排序.
這就是我想要的結(jié)果:
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'),
);
<小時(shí)>
我可以通過運(yùn)行嵌套循環(huán)輕松完成此操作,但這不能很好地?cái)U(kuò)展(我的數(shù)組非常大,并且數(shù)組有更多字段).
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 中沒有為此內(nèi)置函數(shù),我無法想到任何自定義函數(shù),它可以使用 usort 來做到這一點(diǎn).但是 array_map 已經(jīng)足夠簡單了,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);
這篇關(guān)于PHP - 按另一個(gè)數(shù)組對多維數(shù)組進(jìn)行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!