2012-04-24 122 views
0

我有一個數組需要根據其外觀進行排序,因爲它們是按照我的自由意志手動編寫的。注意值暗示將有望出現:PHP排序數組

$options = array("the array retrieved from some forms"); 
    $items = array(); 
    foreach ($options as $key => $val) { 
    switch ($key) { 
     case 'three': 
     $items[]   = "this should come first"; 
     $items[]   = "now the second in order"; 
     $items[]   = "the third"; 
     $items[]   = "forth"; 

     switch ($val) { 
      case 'a': 
      case 'b': 
      $items[]  = "fifth"; 
      $items[]  = "should be six in order"; 
      break; 

      case 'c': 
      default: 
      $items[] = "7 in order"; 
      break; 
     } 

     break; 

...............

正如你看到的值可以是任何東西,但我需要什麼只是基於它們的外觀而爆裂和顯示物品。它的所有手動命令,首先應該打印在頂部。

預計:

"this should come first"; 
"now the second in order"; 
"the third"; 
"forth"; 
"fifth"; 
"should be six in order"; 
"7 in order"; 

當前意想不到:

"should be six in order"; 
"forth"; 
"7 in order"; 
"the third"; 
"fifth"; 
"this should come first"; 
"now the second in order"; 

但我似乎無法適用此http://www.php.net/manual/en/array.sorting.php 排序的任何我懷疑那些$項目某處訂購通過我無法重新排序的形式。我只是有權力按照自上而下的方式編寫輸出和訂單。但是我不能將鍵嵌入$ items中,只是因爲我需要自由地重新排序。

我看了一下輸出,鍵沒有按預期排序。

任何提示都非常感謝。謝謝

+1

當你使用'$ VAR [] = ...;'語法,PHP追加值到數組的末尾。由於腳本的執行順序不符合規則,因此陣列出現故障。 – qJake 2012-04-24 13:07:20

+0

聲音解釋我的問題。謝謝 – swan 2012-04-24 13:23:10

回答

0

php源碼在我們看來的方式與編譯器不同。所以這是不可能的。但是如果你在源代碼上運行正則表達式,這是可能的(不是很好)。

例子:

$source = file_get_contents(__FILE__); 
preg_match_all('#\$items\[\]\s*=\s*"([^"]+)"#', $source, $match); 
// now $match[1] contains the strings. 
$strings = $match[1]; 
+0

完全合法的答案。謝謝 – swan 2012-04-24 13:23:54

+0

這是一個可怕的答案,其他發佈的答案更正確。 – qJake 2012-04-24 13:25:47

2

似乎滿足您陣列的步驟是不是你想要的順序。

也許你可以使用一些技巧來實現你想要

例如Insert「鍵指針」

$ikey = 0; 
$options = array("the array retrieved from some forms"); 
    $items = array(); 
    foreach ($options as $key => $val) { 
    switch ($key) { 
     case 'three': 
     $items[$ikey++]   = "this should come first"; 
     $items[$ikey++]   = "now the second in order"; 
     $items[$ikey++]   = "the third"; 
     $items[$ikey++]   = "forth"; 

     switch ($val) { 
      case 'a': 
      case 'b': 
      $items[$ikey++]  = "fifth"; 
      $items[$ikey++]  = "should be six in order"; 
      break; 

      case 'c': 
      default: 
      $items[$ikey++] = "7 in order"; 
      break; 
     } 

     break; 

我不知道如果這能幫助什麼,因爲你貼uncomplete代碼。

對不起我的英語水平,如果有任何錯誤

+0

謝謝,但恐怕它似乎不起作用 – swan 2012-04-24 13:19:47