给定一个数组: 

$list ['a'] = array (1,2,3); 
$list ['b'] = array (1,2); 
$list ['c'] = array (1,2,3,4);
...

要求输出这样:111,112,113,114,121,122,123.....

以上结果其实就是笛卡尔积下面为我实现的2个版本

1、递归版

<?php

class Cartesian{
    
    public $list = array();

    public $output = array();

    public function __construct($list){
        $this->list = $list;
    }

    public function run(){
        foreach ($this->list[key($this->list)] as $value) {
            $this->coreCal($this->list, $value, 1);
        }
    }

    public function coreCal($list, $content, $deep){
        $i = 0;
        if($deep > count($this->list))
            return;

        foreach ($this->list as $key => $value) {

            if($deep == $i)
            {
                foreach ($value as $iv) 
                {
                    $iv = $content.$iv;
                    if($deep == count($this->list) - 1){
                        $this->output[] = $iv;
                    }else{
                        $this->coreCal($this->list, $iv, $deep+1);
                    }
                }
                break;
            }
            $i++;
        }
        return;
    }

}

$list['a'] = array(1, 2, 3);
$list['b'] = array(1, 2);
$list['c'] = array(1, 2, 3, 4);

$Cartesian = new Cartesian($list);
$Cartesian->run();
print_r($Cartesian->output);

?>
2、指针版:
<?php
    
class Cartesian{
    
    public $list = array();

    public $end_key = "";

    public $output = array();

    public function __construct($list){
        $this->list = $list;
        end($list);
        $this->end_key = key($list);
        $this->coreCal($this->list);
    }

    public function coreCal($list, $str = ""){
        $key = key($list);
        if($key == $this->end_key)
        {
            foreach ($list[$this->end_key] as $value) {
                $this->output[] = $str.$value;
            }
        }else{
            next($list);
            foreach ($list[$key] as $v) {
                $this->coreCal($list, $str.$v);
            }   
        }
    }
}

$list['a'] = array(1, 2, 3);
$list['b'] = array(1, 2);
$list['c'] = array(1, 2, 3, 4);

$Cartesian = new Cartesian($list);

print_r($Cartesian->output);
?>