2012-04-24 119 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