Jump to content

Archived

This topic is now archived and is closed to further replies.

CSmith1128

need some help with arrays.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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 results
echo '<pre>', print_r($data, true), '</pre>';
?>[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.