dimjas Posted March 1, 2007 Share Posted March 1, 2007 Hi, I have for example three arrays: a1=["A","B","c"]; a2=["1","2"]; a3=["x","y","z"]; What I need is this A,1,x A,1,y A,1,z A,2,x A,2,y A,2,z B,1,x .... It will be easy to find all this with foreach function , but I don't know how many arrays I have (I get arrays from mysql_query) and I need some recursive function to find all combinations. Can someone help me to solve this problem? Thanks Link to comment https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/ Share on other sites More sharing options...
effigy Posted March 1, 2007 Share Posted March 1, 2007 You may be able to do this in SQL if you do not join your tables on a specific id, but let them join to every matching row. Link to comment https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/#findComment-197342 Share on other sites More sharing options...
Psycho Posted March 1, 2007 Share Posted March 1, 2007 I was just going to provide a solution whereby you put all the arrays into a single array at first (which would work). But effigy's solution is probably a better approach. Link to comment https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/#findComment-197355 Share on other sites More sharing options...
dimjas Posted March 1, 2007 Author Share Posted March 1, 2007 Hi, I can't change query, I have to use these results. Thank you. Link to comment https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/#findComment-197366 Share on other sites More sharing options...
boo_lolly Posted March 1, 2007 Share Posted March 1, 2007 array_merge() and/or array_merge_recursive() may be of some use. also, do you want to rearrange the array? store all this stuff dynamically into a string? or simply print the contents of the array in that order? Link to comment https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/#findComment-197409 Share on other sites More sharing options...
effigy Posted March 1, 2007 Share Posted March 1, 2007 Try this: <pre> <?php ### Contains all arrays to combine. $arrays = array( array('A', 'B', 'C'), array(1, 2), array('x', 'y', 'z') ); function array_multiple_combo ($arrays) { ### The first array is the first "combination." $combos = array_shift($arrays); ### For the following arrays... foreach ($arrays as $array) { ### Create a new combo between the current $combos ### and the current $array. $new_combos = array(); foreach ($combos as $v1) { foreach ($array as $v2) { $new_combos[] = $v1 . $v2; } } ### Overwrite the old combos with the new. $combos = $new_combos; } return $combos; } print_r(array_multiple_combo($arrays)); ?> </pre> Link to comment https://forums.phpfreaks.com/topic/40765-combinations-of-arrays/#findComment-197457 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.