問題描述
我正在嘗試按另一個數組對多維數組進行排序,但到目前為止還不夠.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模板網!