php generate all combinations from given array

前端 未结 2 858
庸人自扰
庸人自扰 2021-01-06 06:01

What is the simplest way to convert this PHP array

$a = array(\'A\' => array(1, 2),
           \'B\' => array(3, 4),
           \'C\' =>         


        
2条回答
  •  独厮守ぢ
    2021-01-06 06:24

    You can use this function for this request:

    function pc_array_power_set($array) {
        // initialize by adding the empty set
        $results = array(array( ));
    
        foreach ($array as $element)
            foreach ($results as $combination)
                array_push($results, array_merge(array($element), $combination));
    
        return $results;
    }
    

    Usage:

    $set = array('A', 'B', 'C');
    $power_set = pc_array_power_set($set);
    

    Output:

    array( );
    array('A');
    array('B');
    array('C');
    array('A', 'B');
    array('A', 'C');
    array('B', 'C');
    array('A', 'B', 'C');
    

    Resource: http://docstore.mik.ua/orelly/webprog/pcook/ch04_25.htm

提交回复
热议问题