php 使用递归将二维数组将每个数组元素分别与其他数组组合

示例:

public function test(){

        $data = [
            [1,2,3],
            [4,5],
            [6,7]
        ];

        $list = [];
        foreach ($data[0] as $k => $v){
            foreach ($data[1] as $kk => $vv){
                foreach ($data[2] as $kkk => $vvv){
                    $list[] = [$v,$vv,$vvv];
                }
            }
        }

        echo "<pre>";
        print_r($list);

    }

 

用递归方式将示例改造,这样就可以无限制数组长度了

public  $list = [];
    public function test(){

        $data = [
            [1,2,3],
            [4,5],
            [6,7]
        ];

        echo "<pre>";
        $this->arrayRecurse($data,0,[]);
        print_r($this->list);exit;

    }


    private function arrayRecurse($data,$ii,$tmp){
        for ($i = 0;$i < count($data[$ii]);$i ++){
            $j = $ii + 1;
            $tmp[$ii] = $i;

            if($j < count($data)){
                $this->arrayRecurse($data,$j,$tmp);
            }

            if($j == count($data)){
                $t = [];

                for ($x = 0;$x < count($data);$x ++) {
                    $t[] = $data[$x][$tmp[$x]];
                }

                if(!empty($t)){
                    $this->list[] = $t;
                }

            }

        }
    }

 

posted @ 2022-06-30 14:29  zwb_121  阅读(55)  评论(0编辑  收藏  举报