Forza
Forza

Reputation: 1649

PHP sorting script

This may be a bit much to ask here, but what I want are some simple directions or examples of a PHP sorting script, so that I can work it out myself.

I have a webshop where I want my customers to sort their products, bases on some variables such as the price, or color of the product.

I'm building a menu on the left of my site with checkboxes where people can check the variable they want to sort with. When they check a box, the page container must refresh and only the products that match the requirements must be visible. See http://amzn.to/ryeIjF for an example of what I want to achieve.

Note that all the properties of my products are stored in a mysql database.

Upvotes: 0

Views: 1345

Answers (5)

Bhavik Patel
Bhavik Patel

Reputation: 25

Use Order By clause in SQL query like this ORDER BY products or you can sort later by first retrieving result set in array using mysql_fetch_array($result) method

Upvotes: 0

Dutchie432
Dutchie432

Reputation: 29160

Sorting multi-dimensional arrays in PHP is actually not too difficult... I assume that's what you're looking to do (sort by price, popularity, most recent, etc..).

Assume the following structure for a multi-dimensional array $itemsArray

{[
    {
      "id" : "2643",
      "name" : "Leather Jacket",
      "price" : "249.99"
    },
    {
      "id" : "2645",
      "name" : "Suede Jacket",
      "price" : "289.99"
    },
    ...
]}

This can be sorted like...

usort($itemsArray, 'sortItemsByPrice');

function sortItemsByPrice($objA, $objB) {
    //This function returns a -1, 0, or 1 depending on the order  
    //of object A and Object B

    $aVal=$objA['price'];
    $bVal=$objB['price'];
    if ($a == $b) {  
        //or maybe sort on a secondary field
        return 0;    
    }
    return ($a < $b) ? 1 : -1;      
} 

HOWEVER

If you can sort directly in SQL, do so using the ORDER BY keywords in your SQL statement

//Order by price, lowest->highest
SELECT id,name,price FROM products ORDER BY price

//Order by price, highest->lowest
SELECT id,name,price FROM products ORDER BY price desc

Upvotes: 3

Emran
Emran

Reputation: 1031

If your data is stored in MySQL database you can simply sort them when you are querying database. http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html http://php.net/manual/en/function.sort.php I think that better is to, if is possible, deal with data at their source.

Upvotes: 2

dm03514
dm03514

Reputation: 55962

PHP shouldn't be doing the sorting for you. YOu can just make a request to your php script build a SQL query dynamically filter the values selected and have your db do the sorting for you! this is what it is made and optimized to do!!!

Upvotes: 1

Jeremy
Jeremy

Reputation: 2956

Take a look at: http://php.net/manual/en/array.sorting.php

Upvotes: 0

Related Questions