2012-08-08 139 views
1

我想在一個數組「$ to_sort」與問候元素進行排序,以這些元素如何在不同的陣列「$ sorting_order」排序。使用數組作爲排序關係進行排序不同的陣列

不過,我不知道如何處理的情況下,當兩個數組包含不同的元素。

$sorting_order[]=[introduction,skills,education,experience] 
$to_sort[]=[experience,skills,education] 

這是期望的結果:

$sorted[]=[skills,education,experience] 

** SOLUTION: 我得到這個解決方案是,

$sorted = array_intersect($sorting_order, $to_sort); 
print_r($sorted); 

**

回答

1

我想接近它這方法:

1)翻轉a周圍使用array_flip();這將創建一個映射,字符串值作爲鍵和序數值作爲值。

2)使用從1 usort()地圖)。

$amap = array_flip($a); 
usort($b, function($str1, $str2) use ($amap) { 
    $key1 = $amap[$str1]; // decide what to do if the key doesn't exist 
    $key2 = $amap[$str2]; 

    if ($key1 > $key2) { 
     return 1; 
    } elseif ($key1 == $key2) { 
     return 0; 
    } else { 
     return -1; 
    } 
}); 
+0

它會在condotion如果數組大小是不同的,因爲我提到?? – 2012-08-08 06:29:43

+0

它是錯誤的usort行??? – 2012-08-08 06:39:02