[英]Order multiarray based on another array
我有一個數組像
$originalArray = [
...
[
...
'attribute' => 'value'
....
],
[
...
'attribute' => 'year'
....
],
[
...
'attribute' => 'car'
....
],
....
];
我還有另一個數組,它定義了先前數組的所需順序。
$desiredOrderArray = ['car', 'value', 'year'];
我想要的輸出是
$newArrayOrdered = [
[
...
'attribute' => 'car'
....
],
[
...
'attribute' => 'value'
....
],
[
...
'attribute' => 'year'
....
],
];
我正在遍歷數組並以所需順序創建新數組的“重新排序”過程。 有更好的方法嗎? 一些功能或其他
按原樣使用order數組並不是最佳選擇,因為它需要對使用的任何方法進行多個數組搜索。
如果將其翻轉以使其值成為鍵,則在usort
比較函數中將其用作鍵時,可以將屬性用作鍵來查找順序。
$order = ['car', 'value', 'year'];
$order = array_flip($order); // ['car' => 0, 'value' => 1, 'year' => 2]
usort($originalArray, function($a, $b) use ($order) {
return $order[$a['attribute']] <=> $order[$b['attribute']];
});
使用usort
,將不會創建新的數組; 它將對原始數組進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.