2012-08-08 132 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