Home >php教程 >php手册 >假设有如下数组 $words=array("肯","德&q

假设有如下数组 $words=array("肯","德&q

WBOY
WBOYOriginal
2016-06-06 19:39:371270browse

假设有如下数组$words=array(肯,德,基); 数组元素不固定,算所有元素排列组合: 肯德基,肯基德,德肯基等等 肯德,肯基,德肯,德基等等 如数组长度为n,则算出 n字组合 n-1字组合 ...... 2字组合 ?php $num = 4; //数组长度,可自行规定 $arr = array(); //获取

假设有如下数组 $words=array("肯","德","基");
数组元素不固定,算所有元素排列组合:
肯德基,肯基德,德肯基 等等
肯德,肯基,德肯,德基 等等
如数组长度为n,则算出
n字组合
n-1字组合
......
2字组合


<?php


    $num = 4; //数组长度,可自行规定
    $arr = array();

    //获取数组
    for($i=0; $i<$num; $i++) //构建字符数组(用数字字符代替汉字字符)
    {
        $val = $i+1;
        $arr[$i] = "$val" ;
    }

   // $arr = array("肯","德","基");

    $result = pinjie($arr,$arr);

    echo implode(",",$result);  //打印结果未格式化

    function pinjie($baseArr,$selectArr)  //递归函数
    {
        $result = array();
        foreach ($baseArr as $k1 => $v1)
        {
            foreach ($selectArr as $k2 => $v2)
            {
                if (!strstr($v1,$v2))
                {
                    $val = $v1.$v2;
                    $result[] = "$val";
                }
            }
        }

        if (!empty($result))
        {
            $ret = pinjie($result,$selectArr);
        }

        if(!empty($ret))
        {
            $result=array_merge($ret,$result);
        }
        return $result;
    }
?>

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