php 数组组合

WBOY
Release: 2016-06-23 13:56:43
Original
826 people have browsed it

$set = array('a','b','c','d');

该如何把数组组合,输出的结果是
a
b
c
b
ab
ac
ad
bc
bd


回复讨论(解决方案)

$set = array('a','b','c','d');$res = $set;for($i=0, $p=1; $i<count($res) && isset($set[$p]); $i++, $p++) {  $res[] = $res[$i] . $set[$p];}print_r($res);
Copy after login
Copy after login
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => ab
[5] => bc
[6] => cd
)

$set = array('a','b','c','d');$res = $set;for($i=0, $p=1; $i<count($res) && isset($set[$p]); $i++, $p++) {  $res[] = $res[$i] . $set[$p];}print_r($res);
Copy after login
Copy after login
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => ab
[5] => bc
[6] => cd
)


版主这个输出的和楼主的不一样啊,我没太搞懂楼主到底是要怎么组合输出这个数组,我的解决方法如下,这里不用输出cd就可以了
<?php$set = array('a','b','c','d');$len = count($set);$res = array();for($i=0,$k=$len;$i<$len;$i++){  $res[$i] = $set[$i];  for($j=$i+1;$j<$len;$j++){    $res[$k++] = $set[$i].$set[$j];  }}ksort($res);var_dump($res);?>
Copy after login


array (size=10)  0 => string 'a' (length=1)  1 => string 'b' (length=1)  2 => string 'c' (length=1)  3 => string 'd' (length=1)  4 => string 'ab' (length=2)  5 => string 'ac' (length=2)  6 => string 'ad' (length=2)  7 => string 'bc' (length=2)  8 => string 'bd' (length=2)  9 => string 'cd' (length=2)
Copy after login

$set = array('a','b','c','d');$arr=array();for($j=0;$j<sizeof($set);$j++){    $arr[]=$set[$j];}foreach($set as $k=>$v){    for($i=$k;$i<=(3-$v);$i++){        if($v==$set[$i]) continue;        $arr[]=$v.$set[$i];    }}print_r($arr);
Copy after login

Array(    [0] => a    [1] => b    [2] => c    [3] => d    [4] => ab    [5] => ac    [6] => ad    [7] => bc    [8] => bd    [9] => cd)
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template