任意个索引数组的排列组合

1、前言

如何对(任意个)一维索引数组的所有值进行排列组合,使之列出所有的组合情况。

2、例子

本次使用的例子数组是:

$arr = array(array('你','我','他'),array('们是','是'),array('人','神','魔'));

结果显示:

3、代码实现

function getArrSet($arr, $curr_index = -1) 
{
    static $count;//数组总长度
    static $tmp = [];//临时数组
    static $index;//总数组下标
    static $totalArr = [];//总数组

    //第一步,重新初始化前面的4个静态变量
    if($curr_index == -1) {
        $count = sizeof($arr) - 1;//数组下标从0开始
        $tmp = [];
        $index = 0;
        $totalArr = [];
        getArrSet($arr, $curr_index + 1);//调用方法,进行第一次循环
    }else {
        //循环第$current_index层数组
        foreach ($arr[$curr_index] as $v) {
            //当前循环下标小于数组总长度,则需要继续调用方法
            if($curr_index < $count) {
                $tmp[$curr_index] = $v;//将值加入临时数组
                getArrSet($arr, $curr_index + 1);//继续调用方法
            }else {
                $tmp[$curr_index] = $v;//将值加入临时数组
                $totalArr[$index] = $tmp;//将循环完成的临时数组复制给总数组
                $index ++;//总数组下标+1
            }
        }
    }
    return $totalArr;
}

 

posted @ 2017-09-17 21:36  一切随风飘  阅读(751)  评论(0编辑  收藏  举报