need some help with arrays...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
CSmith1128
Forum Newbie
Posts: 2
Joined: Tue Aug 22, 2006 5:52 pm

need some help with arrays...

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Re: need some help with arrays...

Post 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.
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Post Reply