用php过滤搜索结果

Cant really find any useful information on this through Google so hope someone here with some knowledge can help.

I have a set of results which are pulled from a multi dimensional array. Currently the array key is the price of a product whilst the item contains another array which contains all the product details.

key=>Item(name=>test, foo=>bar)

So currently when I list the items I just order by the key, smallest first and it lists the products smallest price first.

However I want to build on this so that when a user sees the results they can choose other ordering options like list all products by a name, certain manufacturer, colour, x ,y ,z etc etc from a drop down box(or something similar)

This is where I need some guidance. Im just not sure how to go about it or best practise or anything. The only way I can think of is to order all the items by the nested array eg by the name, manufacturer etc. but how do I do that in PHP?

Hope you understand what im trying to achieve(if not just ask). Any help on this with ideas, approaches or examples would be great.

Thanks for reading

p.s Im using PHP5

Updated example with a little snippet using in memory database :) P.S: the XSS protection in this example is not needed at all because I check the input as boolean value. To see results in reverse order you specify order?desc

<?php

/* XSS-protection. */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);

$array = array(
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
);

function createTable($db) {
    $db->exec("CREATE TABLE IF NOT EXISTS tags (id INTEGER PRIMARY KEY, tag TEXT NOT NULL UNIQUE)");
}

function insertData($db, $array) {
    $db->beginTransaction();

    foreach($array as $elm) {
        try {
            $stmt = $db->prepare("INSERT INTO tags (tag) VALUES (:tag)");
            $stmt->execute(array(
                ":tag" => $elm
            ));
        } catch(PDOException $e) {
            /*** roll back the transaction if we fail ***/
            $db->rollback();
            /*** echo the sql statement and error message ***/
            echo $sql . '<br />' . $e->getMessage();
        }
    }

    $db->commit();
}

$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
//
createTable($db);
insertData($db, $array);

$order = "ASC";
if (strtoupper($_GET['order']) == "DESC") {
    $order = "DESC";
}

$stmt = $db->prepare("SELECT * FROM tags ORDER BY tag $order");
$stmt->execute();

$data = array();
while($row = $stmt->fetch()) {  
    $data[] = array($row['tag']);
}

echo json_encode($data);

Hope you understand what im trying to achieve(if not just ask). Any help on this with ideas, approaches or examples would be great.

First I have a couple of questions you are saying that you are using PHP5. How do you retrieve your data(RDBMS)? If not, PHP5 has SQLite enabled by default. I think you should be using at least a RDBMS(SQLite/etc) to do the heavy lifting for you.

When you learn SQL you don't have to any sorting in PHP. I think this PDO tutorial while give you insides how to use SQL while doing it safely. SQL is vulnerable to SQL-injections but thanks to PDO's prepared statements you don't have to worry about that anymore.

I have a set of results which are pulled from a multi dimensional array. Currently the array key is the price of a product whilst the item contains another array which contains all the product details.

Use ORDER BY to order. I would use a datatable to do the sorting client-side. Also safes you to do work on the server(PHP). You could for example look at YUI2's datatable.

Sounds like you don't know what you want. Do you want filtering or sorting. Filtering will show only things of a certain type.. sorting will show certain things in order, and by nature, clumped together.

For filtering, loop through the array, before you print the results, check to see if your fields match the criteria.

pseudo code:

foreach $results as $result
  if ($result['type']==$filtertype)
   echo $result['name'];

Edit

For sorting multidimensional arrays, you can use another array to hold the keys and values of the specific column you want to sort, then sort it by value while preserving keys. Then loop through that array to get the keys in the order you want. And use the sorted single dimensional array's keys to access the original results array's values.

foreach ($results as $key=>$data) {
    $sort[$key]=$data['name'];
}
asort($sort);

foreach ($sort as $key=>$value) {
    echo $results[$key]['name'];
    echo $results[$key]['category'];
    //etc etc
}

First, using the prices as keys isn't really the best way to go; if two products have the same price they'll overwrite eachother. It's better to use unique keys (the default ones work) and put the price in the subarray as well.

Then you can use the function usort to sort the array.

$array = array(
  array('price' => 1000, 'name' => 'Expensive and useless stuff'),
  array('price' => 2.3, 'name' => 'Cheap and useful stuff')
);
$sortby = 'price'; // or name, in this example
$code = 'if($product1["'.$sortby.'"] == $product2["'.$sortby.'"]) return 0; return ($func_a < $func_b) ? -1 : 1;';
usort($array, create_function('$product1,$product2', $code));

Source/more info: http://us.php.net/manual/en/function.usort.php