Page 1 of 1

Is an array like a database?

Posted: Sat Mar 31, 2007 3:55 pm
by SmokyBarnable
If I had an array that had price and id for each key and I wanted to find the lowest price in the array how could this be done? Can I query an array like a database?

Posted: Sat Mar 31, 2007 3:58 pm
by feyd
You'll have to search it yourself in some form. It cannot be queried like a database can.

array_multisort() may be of interest.

Posted: Sat Mar 31, 2007 7:04 pm
by clearlinewebdesign
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


If you already have the data in an array, sort the array and then fetch the first element.

If you are getting the product and id from a database, why not only fetch just the relevant row?

e.g.

[syntax="sql"]
SELECT
    id,
    price
FROM
    products
ORDER BY
    price ASC
LIMIT 0, 1
If you have a lot of data already in memory, you could use SQLite:

http://uk2.php.net/sqlite

This takes a bit of setting up and would be a sledgehammer to crack a nut in this case.

A class written in PHP that allowed you to do things like:[/syntax]

Code: Select all

$db = new AllInPHPMemoryDB();

$db->statement('CREATE TABLE products (product varchar(255), price int(10));');

$db->statement('INSERT INTO products SET product = \'widget\', price = 499');
$db->statement('INSERT INTO products SET product = \'sprocket\', price = 599');
$db->statement('INSERT INTO products SET product = \'fubar\', price = 699');

$expensive = $db->query('SELECT * FROM products WHERE price > 550');
where the entire thing was created, used and destroyed each request would be pretty cool. One might argue that it overlaps somewhat with SQLit but it could be useful it some cases. Does anyone know of anything like this that already exists? Or of a way to use SQLite without saving the data in a file?


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]