简体   繁体   中英

Transforming user input into a list array in PHP

I have a textarea field. The output will be a HTML list. Each line will be a new list item. If a user type in a hypen ('-') then the list item will be nested

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

I am not worry about the key values. I then run theme_item_list from http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_item_list To create the list

try this (this has not been tested so it may need a little tweaking):

 $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);
        }      
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM