Page 1 of 1

need some help with arrays...

Posted: Tue Aug 22, 2006 5:56 pm
by CSmith1128
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

Re: need some help with arrays...

Posted: Tue Aug 22, 2006 6:01 pm
by feyd
CSmith1128 wrote:1. how to put items in an array from a loop
rough idea:

Code: Select all

$myArray[] = $myNewValue;
There are several other variations, but that's the one used quite often.
CSmith1128 wrote:2. how to sort and array by the price.
I would perform that in the database query. Have a look at the "ORDER BY" clause in "SELECT" statements for your respective database.

Posted: Wed Aug 23, 2006 1:50 am
by dibyendrah
Hello dear,
Better would be create a associative array in which index will be the item name and the value will be the price.

If you are fetching the price and item from the database, the code will look like below :

Code: Select all

<?php
while ($row = mysql_fetch_array($recordset)) {
$arr_items[ $row['item_name'] ] =  $row['item_price'];
}

rsort($arr_items);

?>
Output of testing without database will be :

Code: Select all

<?php
$arr_items['lemon'] = 50;
$arr_items['orange'] = 20;
$arr_items['banana'] = 50;
$arr_items['apple'] = 40;

rsort($arr_items);
foreach ($arr_items as $key => $val) {
   echo "$key = $val\n";
}
?>

Code: Select all

X-Powered-By: PHP/5.1.1
Content-type: text/html

0 = 20
1 = 40
2 = 50
3 = 50
Cheers,
Dibyendra

Posted: Wed Aug 23, 2006 1:53 am
by RobertGonzalez