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
need some help with arrays...
Moderator: General Moderators
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Re: need some help with arrays...
rough idea:CSmith1128 wrote:1. how to put items in an array from a loop
Code: Select all
$myArray[] = $myNewValue;I would perform that in the database query. Have a look at the "ORDER BY" clause in "SELECT" statements for your respective database.CSmith1128 wrote:2. how to sort and array by the price.
- dibyendrah
- Forum Contributor
- Posts: 491
- Joined: Wed Oct 19, 2005 5:14 am
- Location: Nepal
- Contact:
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 :
Output of testing without database will be :
Cheers,
Dibyendra
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);
?>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 = 50Dibyendra
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA