Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting problem 1

Status
Not open for further replies.

blekfis

Programmer
Oct 19, 2001
38
0
0
SE
I've got an table that looks something like this:

product | price | currency
prod1 | 15 | USD
prod2 | 20 | EUR
prod3 | 89 | GBP
prod4 | 11 | USD

I extract these from the table and then converts them all to EUR, but how do I sort them from low to high (or vv)?
Any code-examples are welcome... ;-)

//N!cklas

 
steps
1. extract each row of the recordset to an array (creating a multidimensional array
2. cycle through converting to base currency
3. sort the multidimensional array

code snippet below

Code:
<?
/*
//use for debugging
$data[] = array ("product"=>"prod1", "price"=>15, "currency"=>"USD");
$data[] = array ("product"=>"prod2", "price"=>50, "currency"=>"EUR");
$data[] = array ("product"=>"prod3", "price"=>22, "currency"=>"GBP");
$data[] = array ("product"=>"prod4", "price"=>30, "currency"=>"YEN");
*/
$tablename = "";
$sql = "Select product, price, currency from $tablename";// enter sql query here
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))	//create an array of arrays by cycling through the recordset
{
  $results_array[] = $row;
}
// convert the amounts into common currency

for ($i=0; $i<count($results_array); $i++)  //iterate through the array and convert to common currency
{
	$results_array[$i]['price'] ==converttoeuros($results_array[$i]['price'], $results_array[$i]['currency']); //assume the currency conversion function takes two vars: the amount and the input currency	
	$results_array[$i]['currency'] = "EUR"; //assuming everything converted to euros this would be a sensible additional step to avoid later confusion
}

// 	now all is converted
//	sort and display
*/
foreach ($results_array as $key => $val) {
   $price[$key]  = $val['price'];
   $currency[$key] = $val['currency']; //the currency code is a bit redundant here as you have already moved everything to a common currency
   $product[$key] = $val['product'];
}

// Sort the data with price ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($price, SORT_ASC, $currency, SORT_DESC, $product, SORT_ASC, $results_array);
print_r($results_array);

?>
 
Thanks a lot!! I was on my way, but some pieces were missing. Now they are all there ;-) Altough I had to change to:
array_multisort($price, SORT_NUMERIC, $currency, SORT_DESC, $product, SORT_ASC, $results_array);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top