[PHP-users 35615] Re: ツリー構造をulとli要素に変換したい

Eiji Miwa miwa @ offside.ne.jp
2011年 8月 6日 (土) 22:11:22 JST


 ミワです。

On 2011/08/05, at 10:47, DM wrote:
> 
> $arrWBS = array("1", "1.1", "1.1.1", "1.2",
> "1.2.1","1.2.1.1","1.2.1.2","1.2.1.3","1.2.1.3.1","1.2.3", "1.3", "1.4", "1.
> 5","1.5.1");
> $rootWBS = "1";
> 
> のような配列(配列はソートされています)と文字列があり、
> それをもとに、
> getWBSHtml($arrWBS,$rootWBS);関数なるものをつくり、
> 
> 上の例($rootWBS = "1";)だと以下のようなHTMLをはき出したいと思っています。


 これでどうでしょうか?

-----
$arrWBS = array('1','1.1','1.1.1','1.2','1.2.1','1.2.1.1','1.2.1.2','1.2.1.3','1.2.1.3.1','1.2.3','1.3','1.4','1.5','1.5.1');
$rootWBS = '1';

define('INDENT_STR', "\t");
function writeWBSHtml($source, $parent, $depth) {
  $pattern = sprintf('/(?:^|,)(%s\.[0-9]+)(?=,|$)/', preg_quote($parent));
  $matches = array();
  if (preg_match_all($pattern, $source, $matches)) {
    printf("%s<ul>\n", str_repeat(INDENT_STR, $depth));
    foreach($matches[1] as $val) {
      printf("%s<li>%s\n", str_repeat(INDENT_STR, $depth+1), $val);
      writeWBSHtml($source, $val, $depth+2);
      printf("%s</li>\n", str_repeat(INDENT_STR, $depth+1));
    }
    printf("%s</ul>\n", str_repeat(INDENT_STR, $depth));
  }
}

sort($arrWBS, SORT_STRING);
writeWBSHtml(implode(',', $arrWBS), $rootWBS, 0);
-----

--
 miwa at offside.ne.jp




PHP-users メーリングリストの案内