silkfire Posted May 6, 2011 Share Posted May 6, 2011 Hey all I've found some combination functions out there but they're not working really like I want. I have an array with some currencies: array('SEK', 'EUR', 'USD', 'GBP', 'DKK', 'NOK', 'ISK'); Now I want the function to generate an array with all possible pairs: array(array('SEK', 'EUR'), array('SEK', 'USD') ...) It must allow for the inverse form: EUR, SEK is different from SEK, EUR. But trash all pairs that are equal: SEK, SEK or EUR, EUR. Help me out? Quote Link to comment https://forums.phpfreaks.com/topic/235684-combination-pairs-of-currencies/ Share on other sites More sharing options...
Adam Posted May 6, 2011 Share Posted May 6, 2011 Not sure I understand how US dollars can be considered a "pair" with Swedish kronor? Edit Sorry, just realised what you meant. Will reply again in a few minutes.. Quote Link to comment https://forums.phpfreaks.com/topic/235684-combination-pairs-of-currencies/#findComment-1211406 Share on other sites More sharing options...
Adam Posted May 6, 2011 Share Posted May 6, 2011 It's a little loopy, but this appears to work: // Loop through each currency foreach ($currencies as $currency) { // Loop through the currencies again to access the others foreach ($currencies as $other_currency) { // Check it's not the same if ($currency == $other_currency) { continue; } // Check this pair doesn't already exist foreach ($currency_pairs as $currency_pair) { if (($currency_pair[0] == $currency && $currency_pair[1] == $other_currency) || ($currency_pair[1] == $currency && $currency_pair[0] == $other_currency)) { continue 2; } } // Add to pairs array $currency_pairs[] = array($currency, $other_currency); } } print_r($currency_pairs); Edit.. again I've actually written that so EUR - SEK, and SEK - EUR are classed as the same. To treat them differently, change the IF to this: if ($currency_pair[0] == $currency && $currency_pair[1] == $other_currency) { continue 2; } Edit.. again.. again Ha.. actually you can just remove the entire foreach loop there if that's the case.. the same order will never come up twice. Quote Link to comment https://forums.phpfreaks.com/topic/235684-combination-pairs-of-currencies/#findComment-1211419 Share on other sites More sharing options...
silkfire Posted May 6, 2011 Author Share Posted May 6, 2011 Oh thank you Adam! So you figured it out? I needed a table for currency conversion but let PHP generate all the combos (much faster, eh?). Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/235684-combination-pairs-of-currencies/#findComment-1211444 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.