2017-12-27 469 views
3

這是我喜歡在一個特定的順序如何將php關聯數組排序爲特定順序?

$aData = Array 
    (
    [break] => Array 
     (
      [Indoor room] => 42 
      [Gym Class] => 19 
     ) 
    [finish] => Array 
     (
      [Indoor room] => 42 
      [Gym Class] => 19 
     ) 

    [lunch] => Array 
     (
      [Indoor room] => 7 
     ) 

    [period1] => Array 
     (
      [Indoor room] => 12 
      [Gym Class] => 22 
     ) 

    [period2] => Array 
     (
      [Gym Class] => 14 
      [Indoor room] => 25 
     ) 

    [period3] => Array 
     (
      [Gym Class] => 21 
      [Indoor room] => 11 
     ) 

    [period4] => Array 
     (
      [Gym Class] => 22 
      [Indoor room] => 20 
     ) 

    [period5] => Array 
     (
      [Gym Class] => 16 
      [Indoor room] => 9 
     ) 

) 

排序的數組,但我喜歡它的順序是:

break, period1, period2, lunch, period3, period5, period6, finish 

這個我想下面的PHP代碼

$arraySort = [ 
    "break", 
    "period1", 
    "period2", 
    "period3", 
    "lunch", 
    "period4", 
    "period5", 
    "period6", 
    "finish" 
]; 

    foreach($aData as $period => $catsScore){ 
    echo 'test '.$period.'<br/>'; 
    $periodItem = [$period]; 
    foreach($arraySort as $cat){ 
     echo 'new: '.$cat.'<br/>'; 
     $periodItem[] = $catsScore; 
    } 
    $output[] = $periodItem; 
    } 


print_r($output); 

回答

2

Easy-只需使用arraySort作爲關鍵字,從原來的陣列得到相應的陣列/值,

<?php 

$arraySort = [ 
    "break", 
    "period1", 
    "period2", 
    "period3", 
    "lunch", 
    "period4", 
    "period5", 
    "period6", 
    "finish" 
]; 

$final_array = []; 

foreach($arraySort as $arraySo){ 
    $final_array[$arraySo] = $aData[$arraySo]; 
} 

print_r($final_array); 

輸出: - https://eval.in/926361

+0

感謝活着,這是一個我明白了。你只需使用arraySort作爲assoc鍵並從原始數組中獲取相應的數組/值,對嗎? – alex

+0

@alex是的。這很容易 –

+0

array_combine更快,看起來更簡單,IMO。 – Alex

0

您可以使用array_combine用於此目的:

$arrary_sort = ["break", "period1"]; 
$final_array = array_combine($array_sort, $your_array_here); 
+2

這將只是「重命名」現有的價值觀,不正確地重新排序它們 –

+0

您更改了鍵但不重新排列陣列 – splash58

1

請正確有序陣列和值填充源陣列

$final_array = array_replace(array_fill_keys($arraySort, []), $aData); 

demo