2016-04-27 141 views
0

是否有一種簡單的方法來對具有用於此任務的可變數組的數組進行排序? 例如:PHP - 使用另一個陣列對數組進行排序

$fruits [ 
    'Apple' => '12', 
    'Cherry' => '10', 
    'Lemon' => '34', 
    'Peach' => '6' 
] 

$order [ 
    1 => 'Peach', 
    2 => 'Other', 
    3 => 'Lemon', 
    4 => 'Other2', 
    5 => 'Apple', 
    6 => 'Cherry', 
    7 => 'Other3' 
] 

我想退掉這類型的數組:

$ordered_fruits [ 
    'Peach' => '6', 
    'Lemon' => '34', 
    'Apple' => '12', 
    'Cherry' => '10' 
] 
+0

見陣列的這個例子結合功能可能會幫助 http://www.w3schools.com/php/showphp。 asp?filename = demo_func_array_combine –

+1

沒有排序,只是搜索並創建一個新陣列。 –

回答

4
$ordered_fruits = array(); 
foreach($order as $value) { 

    if(array_key_exists($value,$fruits)) { 
     $ordered_fruits[$value] = $fruits[$value]; 
    } 
} 
+1

太棒了,我花了一點時間給出答案。 –

3

用PHP功能使它:

$new = array_filter(array_replace(array_fill_keys($order, null), $fruits)); 
+0

PHP函數是多麼有趣......,我們做了很多代碼,並且使用了一些庫函數。 –

+0

是的,它的圖書館有這麼多的樂趣,如果不是這樣我忘了他們的一半:) – splash58

1

排序的技術:

$result = array(); 

foreach($order as $value){ 
    if(array_key_exists($value, $fruits)){ 
     $result[$value] = $fruits[$value]; 
    } 
} 

結果

print_r($result); 

Array 
(
    [Peach] => 6 
    [Lemon] => 34 
    [Apple] => 12 
    [Cherry] => 10 
) 
2

試試這個:

$fruits = array(
    'Apple' => '12', 
    'Cherry' => '10', 
    'Lemon' => '34', 
    'Peach' => '6' 
); 

$order = array(
    1 => 'Peach', 
    2 => 'Other', 
    3 => 'Lemon', 
    4 => 'Other2', 
    5 => 'Apple', 
    6 => 'Cherry', 
    7 => 'Other3' 
); 

$result = array(); 
foreach ($order as $key => $value) { 
    if (array_key_exists($value, $fruits)) { 
    $result[$value] = $fruits[$value]; 
    } 
} 
print_r($result); 
+0

好工作........ –