Php generates all combinations from a given array

What is the easiest way to convert this PHP array

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

in it:

 $result = array( array('A' => 1, 'B' => 3, 'C' => 5), array('A' => 1, 'B' => 4, 'C' => 5), array('A' => 2, 'B' => 3, 'C' => 5), array('A' => 2, 'B' => 4, 'C' => 5), ); 

$a can have many different keys that I don't know at design time. Therefore, I need to generate all the combinations in the given array.

UPDATE:

I need to generate URLs based on an incoming array. Therefore, I do not know how many parameters I will receive during development. I have only an array of parameters, it could be, for example,

 $a = array('A' => array(5,3, 1)); 
Result

will be:

 $result = array( array('A' => 5), array('A' => 3), array('A' => 1)); 

or

 $a = array('X' => array(5), 'D' => array(4, 7)); 
Result

will be:

 $result = array( array('X' => 5, 'D' => 4), array('X' => 5, 'D' => 7)); 
+4
source share
2 answers

Like this:

 $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; } 

Exit

 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 
+6
source

You can use this function for this query:

 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; } 

Using:

 $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

0
source

Source: https://habr.com/ru/post/1494231/


All Articles