Cruisecar Posted May 25, 2008 Share Posted May 25, 2008 Firstly thanks for reading! I Have an Array($options) - [9] = [12], [18], [20] [12] = [3], [6] [18] = [19], [13] Basically I want something that can give me all of the possible combinations. within a loop - 1 = 12,3,19 2 = 12,3,13 e.t.c. while(something){ $x++; $insert = "insert into table(`id`,`option`,`value`) values('x','x','x'); $insert = "insert into table(`id`,`option`,`value`) values('x','x','x'); $insert = "insert into table(`id`,`option`,`value`) values('x','x','x'); } So the first combination would be entered as 3 rows into the database as so: $insert = "insert into table(`id`,`option`,`value`) values('100','9','12'); $insert = "insert into table(`id`,`option`,`value`) values('100','12','3'); $insert = "insert into table(`id`,`option`,`value`) values('100,'18','19'); Next lot: $insert = "insert into table(`id`,`option`,`value`) values('101','9','12'); $insert = "insert into table(`id`,`option`,`value`) values('101','12','3'); $insert = "insert into table(`id`,`option`,`value`) values('101','18','13'); Hope somebody can help me. It needs to be something that works no matter how many values there are within the array. Link to comment https://forums.phpfreaks.com/topic/107221-combinations-problem/ Share on other sites More sharing options...
sasa Posted May 25, 2008 Share Posted May 25, 2008 try <?php $options = array( 9 => array(12, 18, 20), 12 => array(3, 6), 18 => array(19, 13) ); $total_comb = 1; $keys = array(); $key_count = array(); $out = array(); foreach ($options as $k => $v){ $keys[] = $k; $total_comb *= count($v); $key_count[$k] = count($v); } $keys = array_reverse($keys); for ($x = 0; $x < $total_comb; $x++){ $i = $x; $tmp = array(); foreach ($keys as $k){ $a = $i % $key_count[$k]; $i = (int) ($i / $key_count[$k]); $tmp[] = array('option' => $k,'value' => $options[$k][$a]); } $out[] = array_reverse($tmp); } print_r($out); ?> Link to comment https://forums.phpfreaks.com/topic/107221-combinations-problem/#findComment-549741 Share on other sites More sharing options...
Barand Posted May 25, 2008 Share Posted May 25, 2008 try <?php $a = array ('a1', 'a2', 'a3', 'a4'); $b = array ('b1', 'b2'); $c = array ('c1', 'c2', 'c3'); for ($x=0, $ka=count($a); $x < $ka; $x++) { for ($y=0, $kb=count($b); $y < $kb; $y++) { for ($z=0, $kc=count($c); $z < $kc; $z++) { echo "$a[$x] $b[$y] $c[$z] <br/>"; } } } ?> gives--> a1 b1 c1 a1 b1 c2 a1 b1 c3 a1 b2 c1 a1 b2 c2 a1 b2 c3 a2 b1 c1 a2 b1 c2 a2 b1 c3 a2 b2 c1 a2 b2 c2 a2 b2 c3 a3 b1 c1 a3 b1 c2 a3 b1 c3 a3 b2 c1 a3 b2 c2 a3 b2 c3 a4 b1 c1 a4 b1 c2 a4 b1 c3 a4 b2 c1 a4 b2 c2 a4 b2 c3 Link to comment https://forums.phpfreaks.com/topic/107221-combinations-problem/#findComment-549742 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.