Home > Backend Development > PHP Tutorial > 怎么得到这个组合?得到排列组合结果

怎么得到这个组合?得到排列组合结果

WBOY
Release: 2016-06-13 13:47:04
Original
1072 people have browsed it

如何得到这个组合?得到排列组合结果
属性:颜色 红,黄,蓝。。。。 
  大小 大,小 。。。。 
  容量 1G,2G,3G,5G 。。。 
  。。。。。。。。。 
   

要求得到各个属性值的所有组合: 
比如 红大,红小,红大1G,红小1G,红小2G。。。蓝大,。。 蓝1G。。。。 



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

PHP code
<?php $color  =   array("红", "黄", "蓝");
$size   =   array("大", "小");
$cap    =   array("1G", "2G", "3G", "5G");

$foo    =   array($color, $size, $cap);

function get_all($e)
{
    $elem_total = count($e);
    $max = 1;
    for ($i=0; $i<$elem_total; $i++) {
        $len = count($e[$i])+1;
        $elem_size[] = $len;
        $max *= $len;
    }   
    for ($i=1; $i<$max; $i++) {
        $m = $i; 
        $item = ""; 
        $ct = 0;
        for ($j=0; $j<$elem_total; $j++) {
            $n = $m%$elem_size[$j];
            $item .= $n>0?$e[$j][$n-1]:"";
            $ct += $n>0?1:0;
            $m = (int)($m/$elem_size[$j]);
        }   
        if ($ct>=2)
            $all[] = $item;
    }   
    return $all;
}

$ret = get_all($foo);
print_r($ret);

?> <div class="clear">
                 
              
              
        
            </div>
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