CSmith1128 Posted August 22, 2006 Share Posted August 22, 2006 hey..i need some help with arrays.here's what i need to do...-i have prices stored in a db.-i would like to have 2 arrays.-i need to store the price in one array then the item name in another array.-then i need to sort the array by price starting from the highest price to the lowest price.can someone help?!basically i need a general idea of..1. how to put items in an array from a loop and 2. how to sort and array by the price.thanks!Chris Quote Link to comment Share on other sites More sharing options...
hitman6003 Posted August 22, 2006 Share Posted August 22, 2006 I would use a single array, with the prices being the key and the item being the value. Then you can use the ksort (http://www.php.net/ksort) and krsort (http://www.php.net/krsort) functions.As for getting values in an array:[code]<?php$query = "SELECT price, item FROM table";$result = mysql_query($query) or die(mysql_error());while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $price = $row['price']; $data[$price] = $row['item'];}ksort($data);echo '<pre>';print_r($data);?>[/code] Quote Link to comment Share on other sites More sharing options...
HeyRay2 Posted August 22, 2006 Share Posted August 22, 2006 What if you have two items with identical prices?[b]Apples = 5[/b][b]Oranges = 5[/b]You'll overwrite a previous index.Why do sorting after your DB query? Why not just let the query do the sorting?[code]<?php$query = "SELECT price, item FROM table ORDER BY price DESC";$result = mysql_query($query) or die(mysql_error());while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo $row['item'].' - '.$row['price'].'<br />';}?>[/code] Quote Link to comment Share on other sites More sharing options...
Barand Posted August 22, 2006 Share Posted August 22, 2006 And if you really want an array[code]<?php$query = "SELECT price, item FROM table";$result = mysql_query($query) or die(mysql_error());while (list($price, $item) = mysql_fetch_row($result)) { $data[$item] = $price;}arsort ($data); // sort desc preserving keys// check resultsecho '<pre>', print_r($data, true), '</pre>'; ?>[/code] Quote Link to comment 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.