Finding cartesian product with PHP associative arrays

前端 未结 10 1880
醉梦人生
醉梦人生 2020-11-22 04:17

Say that I have an array like the following:

Array
(
    [arm] => Array
        (
            [0] => A
            [1] => B
            [2] => C
         


        
10条回答
  •  悲哀的现实
    2020-11-22 04:39

    Another solution:

    function getAllVariations($input) {
        $result = array();
        $cnt = array_product(array_map('count', $input));
        $step = 1;
        foreach ($input as $key=>$array) {
            for ($i=0; $i<$cnt; $i++) {
                foreach ($array as $value) {
                    for ($k=0; $k<$step; $k++) {
                        $result[$i+$k][$key] = $value;
                    }
                    $i += $step;
                }
                $i--;
            }
            $step = $step * count($array);
        }
        return $result;
    }
    

    Usage:

    $input = array(
        'arm' => array('A', 'B', 'C'),
        'gender' => array('Female', 'Male'),
        'location' => array('Vancouver', 'Calgary'),
        'name' => array('Rio', 'Mark')
    );
    
    echo "
    ";
    var_dump(getAllVariations($input));
    

提交回复
热议问题