2013-02-26 153 views
5

我有一個數組:重新安排PHP關聯數組

$example = array(); 

$example ['one'] = array('first' => 'blue', 
          'second' => 'red'); 

$example ['two'] = array('third' => 'purple', 
          'fourth' => 'green'); 

$example ['three'] = array('fifth' => 'orange', 
          'sixth' => 'white'); 

基於某些輸入到函數中,我需要改變示例數組的順序foreach循環處理我的輸出之前:

switch($type) 

case 'a': 
//arrange the example array as one, two three 
break; 

case 'b': 
//arrange the example array as two, one, three 
break; 

case 'c': 
//arrange the example array in some other arbitrary manner 
break; 

foreach($example as $value){ 
     echo $value; 
} 

有沒有簡單的方法來做到這一點,而無需重新設計我所有的代碼?我有一個相當深入的foreach循環來處理,如果有簡單的方法可以簡單地重新排序數組,每次都會非常有用。

+2

你的「任意數組排序?」的目的是什麼?你只是試圖隨機化訂單?或者,你是否特別想以參數化的方式轉移項目? – user1477388 2013-02-26 21:23:37

+0

我想問題的關鍵是我需要對它們進行排序,並且不會落入任何現成的排序標準,如字母或數字......我需要將它按照我如何分類進行排序。 – absentx 2013-02-26 21:55:24

回答

2

您可以使用array_multisort爲您置換。我假設你知道這個排列,並且不需要從關鍵名字中派生出來。比方說,要順序two, three, one,然後創建參考陣列那樣:

$permutation = array(3, 1, 2); 

含義:第一項移到位置3,第二項到位置1,第三個項目到位置2

然後,switch,置換後:

array_multisort($permutation, $example); 

這將排序$permutation陣列和應用相同的順序$example

+0

因爲我沒有使用數字鍵將排列數組的工作?這似乎是我採取的路線,因爲你是絕對正確的,因爲我知道每種情況下我想要的排列組合。 – absentx 2013-02-26 23:20:05

+0

它與按鍵無關,array_multisort保留非數字鍵,所以:是的,它會工作 – 2013-02-26 23:21:52

+0

是的,這是做到這一點的方式,再次感謝。花了一點時間把我的頭圍繞在排列上(一段時間不必使用它們),但最終這是最簡單的方法,因爲我知道每個案例的順序。 – absentx 2013-02-26 23:46:24

0

您需要爲每種情況編寫自定義排序功能,然後使用。第一種情況可能只是使用排序。任意排序需要是您定義的邏輯。

2

你不會在這裏找到一個銀色的子彈答案。您可能需要編寫自己的函數以便與uksort()一起使用。

uksort($example, function ($a, $b) use $type { 
    switch($type) { 
     case 'a': 
      if ($a === 'one' || $b === 'three') return 1; 
      if ($a === 'three' || $b === 'one') return -1; 
      if ($a === 'two' && $b === 'three') return 1; 
      return -1; 
      break; 
     // and so on... 
    } 
}); 
0

我看到更多的方法來解決這個問題,但不知道更多關於我不知道什麼更好。

  1. 做一個預評分(爲每個元件的數值,在「相當深入foreach循環」計算),然後用它作爲主要單由標準它對數組進行排序。

  2. 如果您的基準 - S僅基於數值型字段,ASC/DESC使用http://php.net/manual/en/function.array-multisort.php

  3. 讓自定義排序功能對每一種情況下(http://www.php.net/manual/en/function.usort.php