php generate all combinations from given array

前端 未结 2 767
庸人自扰
庸人自扰 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:26

    Like this one:

    $a = array('A' => array(1, 2),
               'B' => array(3, 4),
               'C' => array(5));
    
    function get_combinations($arrays) {
        $result = array(array());
        foreach ($arrays as $property => $property_values) {
            $tmp = array();
            foreach ($result as $result_item) {
                foreach ($property_values as $property_value) {
                    $tmp[] = array_merge($result_item, array($property => $property_value));
                }
            }
            $result = $tmp;
        }
        return $result;
    }
    

    Output

    var_dump(get_combinations($a));
    
    array (size=4)
      0 => 
        array (size=3)
          'A' => int 1
          'B' => int 3
          'C' => int 5
      1 => 
        array (size=3)
          'A' => int 1
          'B' => int 4
          'C' => int 5
      2 => 
        array (size=3)
          'A' => int 2
          'B' => int 3
          'C' => int 5
      3 => 
        array (size=3)
          'A' => int 2
          'B' => int 4
          'C' => int 5
    

提交回复
热议问题