php 数组组合
$set = array('a','b','c','d');
该如何把数组组合,输出的结果是
a
b
c
b
ab
ac
ad
bc
bd
------解决方案--------------------
$set = array('a','b','c','d');<br />$res = $set;<br />for($i=0, $p=1; $i<count($res) && isset($set[$p]); $i++, $p++) {<br /> $res[] = $res[$i] . $set[$p];<br />}<br />print_r($res);Array
<?php<br />$set = array('a','b','c','d');<br />$len = count($set);<br />$res = array();<br />for($i=0,$k=$len;$i<$len;$i++){<br /> $res[$i] = $set[$i];<br /> for($j=$i+1;$j<$len;$j++){<br /> $res[$k++] = $set[$i].$set[$j];<br /> }<br />}<br />ksort($res);<br />var_dump($res);<br />?>
array (size=10)<br /> 0 => string 'a' (length=1)<br /> 1 => string 'b' (length=1)<br /> 2 => string 'c' (length=1)<br /> 3 => string 'd' (length=1)<br /> 4 => string 'ab' (length=2)<br /> 5 => string 'ac' (length=2)<br /> 6 => string 'ad' (length=2)<br /> 7 => string 'bc' (length=2)<br /> 8 => string 'bd' (length=2)<br /> 9 => string 'cd' (length=2)<br />
<br />$set = array('a','b','c','d');<br />$arr=array();<br />for($j=0;$j<sizeof($set);$j++){<br /> $arr[]=$set[$j];<br />}<br />foreach($set as $k=>$v){<br /> for($i=$k;$i<=(3-$v);$i++){<br /> if($v==$set[$i]) continue;<br /> $arr[]=$v.$set[$i];<br /> }<br />}<br />print_r($arr);<br />
<br />Array<br />(<br /> [0] => a<br /> [1] => b<br /> [2] => c<br /> [3] => d<br /> [4] => ab<br /> [5] => ac<br /> [6] => ad<br /> [7] => bc<br /> [8] => bd<br /> [9] => cd<br />)<br /><br />