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 Link to comment https://forums.phpfreaks.com/topic/18353-need-some-help-with-arrays/ 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] Link to comment https://forums.phpfreaks.com/topic/18353-need-some-help-with-arrays/#findComment-78895 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] Link to comment https://forums.phpfreaks.com/topic/18353-need-some-help-with-arrays/#findComment-78907 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] Link to comment https://forums.phpfreaks.com/topic/18353-need-some-help-with-arrays/#findComment-78913 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.