Home  >  Article  >  Backend Development  >  高手来字符串组合有关问题

高手来字符串组合有关问题

WBOY
WBOYOriginal
2016-06-13 12:58:02955browse

高手来字符串组合问题
注意(其中#和$数量不定,也就是说层数不定,用固定的循环肯定是做不到的)

原始字符串如下:
a$b$c#A$B$C#1$2$3
要求组合出来N个字符串 ,用逗号连接
aA1,aA2,aA3,aB1,aB2,aB3,aC1,aC2,aC3,bA1,bA2,bA3,bB1,bB2,bB3,bC1,以此类推。

再提供几个字符串:
a$b$c#A$B$C#1$2$3#y$u$u
a$b$c#A$B$C$D$E$F#1$2$3#y$u$u#0$9$8$7$6$5
字符串不固定,没有什么规律的。


------解决方案--------------------

$s = 'a$b$c#A$B$C#1$2$3';<br />
<br />
foreach(explode('#', $s) as $v) {<br />
  $t[] = explode('$', $v);<br />
}<br />
<br />
echo join(',', foo($t));<br />
<br />
function foo($ar) {<br />
  $t = array_shift($ar);<br />
  if(count($ar) > 1) {<br />
    $r = foo($ar);<br />
  }else $r = current($ar);<br />
  foreach($t as $t1) {<br />
    foreach($r as $r1) {<br />
      $res[] = $t1.$r1;<br />
    }<br />
  }<br />
  return $res;<br />
}


aA1,aA2,aA3,aB1,aB2,aB3,aC1,aC2,aC3,bA1,bA2,bA3,bB1,bB2,bB3,bC1,bC2,bC3,cA1,cA2,cA3,cB1,cB2,cB3,cC1,cC2,cC3

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn