common Posted July 13, 2009 Share Posted July 13, 2009 Hi all, Im struggling with arrays.Say I have two arrays: array1 = array('one','two','three','four','five'); array2 = array('a','b','c','d'); If I want to choose random combination of these two arrays, but want to keep the combinations unique, for example I have 'one' from array1 and 'c' from array2, but I want many combinations... but not the same as 'one' from array1 and 'c' from array2...does anyone know how to do this?? Quote Link to comment https://forums.phpfreaks.com/topic/165837-2-arrays/ Share on other sites More sharing options...
aggrav8d Posted July 13, 2009 Share Posted July 13, 2009 foreach($array1 as $a) { $b=$array2[rand()%count($array2)]; // $a / $b is now your random pair? } Quote Link to comment https://forums.phpfreaks.com/topic/165837-2-arrays/#findComment-874741 Share on other sites More sharing options...
p2grace Posted July 13, 2009 Share Posted July 13, 2009 Is there supposed to be an equal number of values in each array? If so you could just do an array_shuffle to each and then one for loop to get the value of each key. Quote Link to comment https://forums.phpfreaks.com/topic/165837-2-arrays/#findComment-874744 Share on other sites More sharing options...
Psycho Posted July 13, 2009 Share Posted July 13, 2009 If I want to choose random combination of these two arrays, but want to keep the combinations unique, To ensure the results are unique you could either create a new array of all the combinations or create a process that will keep track of the previous combinations and ensure there are no duplicates. The process I would use would depend on how big I expect those two arrays to be and how many combinations I expect to retrieve Quote Link to comment https://forums.phpfreaks.com/topic/165837-2-arrays/#findComment-874779 Share on other sites More sharing options...
Psycho Posted July 13, 2009 Share Posted July 13, 2009 The following function will return a multidimentional array of every combination between array1 and array2. You could then do an array_rand to radomize the order of the combinations. Then get however many unique pairs that you need. function arrayJoin($array1, $array2) { $combinedArray = array(); foreach ($array1 as $value1) { foreach ($array2 as $value2) { $combinedArray[] = array($value1, $value2); } } return $combinedArray; } Quote Link to comment https://forums.phpfreaks.com/topic/165837-2-arrays/#findComment-874794 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.