2011-03-23 142 views
0

我有一個textarea字段。輸出將是一個HTML列表。每一行將是一個新的列表項。如果用戶輸入一個hypen(' - '),則列表項將被嵌套將用戶輸入轉換爲PHP中的列表數組

Sample 
test1 
te-st2 
-test3 
-test4 
--test5 
--test6 
-test7 
test8 
-test9 
test10 

Output should be 
Array (test1, 
     te-st2, 
     array(test3, 
      test4, 
      array(test5, test6), 
      test7 
     ), 
     test8, 
     array(test9), 
     test10 

我不擔心關鍵值。 我再從http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_item_list 運行theme_item_list創建列表

+0

將這份名單隻列出3或者是N + – Prisoner 2011-03-23 16:57:29

+0

@Prisoner它的N – iStryker 2011-03-23 17:15:58

回答

1

試試這個(這還沒有經過測試,因此它可能需要一些調整):

$sample = "test1 
te-st2 
-test3 
-test4 
--test5 
--test6 
-test7 
test8 
-test9 
test10" 

$arr = explode("\n",$sample); 
foreach($arr as $key=>$val){ 
    if($val[0] == '-'){ 
     unset($val[0]); 
     if($val[1] == '-'){ 
      unset($val[0]); 
      unset($arr[$key]); 
      $arr[$key-1][] = $val; 
     } 
     else { 
      $arr[$key] = array($val); 
     }  
    } 
} 
+0

無法解除($ val [0])導致致命錯誤 – iStryker 2011-03-23 18:03:39

+0

是的。抱歉。你必須用字符串替換第一個字母而不是那個。正如我上面所說的那樣,這沒有經過嚴格測試 – Neal 2011-03-23 18:04:19