2012-09-14 33 views
6

我有一個月份名稱數組,如目前的訂單(「四月」,「八月」,「二月」)等我想重新排列這個列表,使它在一個(「一月」,「二月」,「三月」)的正常月份順序PHP重新排列月份名稱的排列

該數組正在從SHOW TABLES sql查詢填充,不幸的是,SHOW TABLES沒有ORDER BY參數,所以我認爲我的最佳打賭是將它們添加到數組並重新排列數組以獲得我正在尋找的內容。

+0

的順序列表你是說你有一個每月表?如果是這樣:爲什麼? – PeeHaa

+0

每個月有一張桌子似乎是一個嚴重的數據庫設計問題。 –

回答

14

將月份轉換爲數值。再下訂單數字使用sort()

數組您就可以使用這樣一個問題:convert month from name to number

@馬修的答案似乎運作良好:

$date = date_parse('July');; 
echo $date["month"]; 

工作液

$months = array("April", "August", "February"); 

usort($months, "compare_months"); 
var_dump($months); 

function compare_months($a, $b) { 
    $monthA = date_parse($a); 
    $monthB = date_parse($b); 

    return $monthA["month"] - $monthB["month"]; 
} 
+0

這工作非常好!謝謝! – Ron

0

這是不可能將數組排序爲獨立數組,因爲系統沒有kn的方法因爲,今年1至上,其次是二月,等等。你可以定義最初的哈希,像

a = {'January':0,'February':1,...'December':11} 

然後你就可以以這種方式

array_to_be_sorted = sorted(array_to_be_sorted, key = lambda(x): a[x]) 
1
$input = array('May', 'December', 'March', 'July'); 
$output = array(); 

foreach($input as $month) { 
    $m = date_parse($month); 
    $output[$m['month']] = $month; 
} 
ksort($output); 

var_dump($output); 

輸出

排序的數組
array 
    3 => string 'March' (length=5) 
    5 => string 'May' (length=3) 
    7 => string 'July' (length=4) 
    12 => string 'December' (length=8) 
1

這是一個稍微優化的版本(沒有日期解析)^^

$foobar_months = array('april','februari', 'march', 'may', 'june', 'januari', 'august', 'october', 'july', 'november', 'december', 'september'); 
usort($foobar_months, "sortMonths"); 
var_dump($foobar_months); 

function sortMonths ($a, $b) { 
    $months = array('januari', 'februari', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'); 
    if (array_search($a, $months) == array_search($b, $months)) return 0; 
    return array_search($a, $months) > array_search($b, $months) ? 1 : -1; 
} 
0

你可以按照下面的步驟

  1. 獲取SHOW表的輸出,這將是個月的聯合國訂單列表(「四月」,「八五」,「二月」 )
  2. 通過這個來切換case如下
    $ output_show_tables =(「April」,「August」,「February」) $ order_month_list = array(); 的foreach($ output_show_tables爲$月){

開關($月) 情況下'1月份: $ order_month_list [1] =月1日;打破; $ order_month_list [2] =二月;打破; .. ... $ order_month_list [12] = December;打破;

}

  1. 現在你得到個月