Reputation: 5520
I have string like this:
EUR-USD,USD-EUR,SEk-CAD
I want to make this to an array and sort by second currency and I want to the result to be
SEk-CAD,USD-EUR,EUR-USD
(Sorted by CAD, EUR and USD)
This is my attempt and it works, but I'm wondering if I'm not "overdoing" this? Anyone has an easier/better solution to achieve this?
Second currency
Create an array of currency pairs:
array (size=3)
0 =>
array (size=2)
0 => string 'EUR' (length=3)
1 => string 'USD' (length=3)
1 =>
array (size=2)
0 => string 'USD' (length=3)
1 => string 'EUR' (length=3)
2 =>
array (size=2)
0 => string 'SEk' (length=3)
1 => string 'CAD' (length=3)
Reverse order of currencies pairs in above array and put them into a non mutlidimensional array:
array (size=3)
0 => string 'USD-EUR' (length=7)
1 => string 'EUR-USD' (length=7)
2 => string 'CAD-SEk' (length=7)
Sort the array (with sort()
) and glue that array into a new string
string 'CAD-SEk,EUR-USD,USD-EUR' (length=23)
Make an array of currency pairs from the newly created string:
array (size=3)
0 =>
array (size=2)
0 => string 'CAD' (length=3)
1 => string 'SEk' (length=3)
1 =>
array (size=2)
0 => string 'EUR' (length=3)
1 => string 'USD' (length=3)
2 =>
array (size=2)
0 => string 'USD' (length=3)
1 => string 'EUR' (length=3)
Reverse order of currencies pairs in above array and put them into a non mutlidimensional array:
array (size=3)
0 => string 'SEk-CAD' (length=7)
1 => string 'USD-EUR' (length=7)
2 => string 'EUR-USD' (length=7)
Glue the array together into a final string:
string 'SEk-CAD,USD-EUR,EUR-USD' (length=23)
Upvotes: 0
Views: 30
Reputation: 8618
Try this:
$currency_string = "EUR-USD,USD-EUR,SEk-CAD";
$currency_array = explode(",", $currency_string);
function compare($a, $b) {
$a = explode("-", $a);
$b = explode("-", $b);
if ($a[1] === $b[1]){
return 0;
}
return ($a[1] < $b[1]) ? -1 : 1;
}
usort($currency_array, "compare");
$final_currency_string = implode(",", $currency_array);
echo $final_currency_string; // Prints SEk-CAD,USD-EUR,EUR-USD
Hope this helps.
Upvotes: 2