Jump to content

need some help with arrays.


CSmith1128

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.