Jump to content


Photo

need some help with arrays.


  • Please log in to reply
3 replies to this topic

#1 CSmith1128

CSmith1128
  • Members
  • PipPipPip
  • Advanced Member
  • 46 posts

Posted 22 August 2006 - 10:57 PM

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


#2 hitman6003

hitman6003
  • Members
  • PipPipPip
  • Advanced Member
  • 1,807 posts

Posted 22 August 2006 - 11:00 PM

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:

<?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);
?>


#3 HeyRay2

HeyRay2
  • Members
  • PipPipPip
  • Advanced Member
  • 223 posts

Posted 22 August 2006 - 11:25 PM

What if you have two items with identical prices?

Apples = 5
Oranges = 5

You'll overwrite a previous index.

Why do sorting after your DB query? Why not just let the query do the sorting?

<?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 />';
}

?>


#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 22 August 2006 - 11:52 PM

And if you really want an array
<?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 results
echo '<pre>', print_r($data, true), '</pre>'; 
?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users