简体   繁体   English

用php过滤搜索结果

[英]filtering search results with php

Cant really find any useful information on this through Google so hope someone here with some knowledge can help. 不能通过Google真的找到任何有用的信息,因此希望这里的知识渊博的人能为您提供帮助。

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) 但是我希望以此为基础,以便当用户看到结果时,他们可以选择其他订购选项,例如从下拉框(或类似的东西)按名称,某些制造商,颜色,x,y,z等列出所有产品)

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? 我能想到的唯一方法是通过嵌套数组排序所有项目,例如名称,制造商等,但我如何在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 谢谢阅读

ps Im using PHP5 ps我使用PHP5

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. 然后,您可以使用函数usort对数组进行排序。

$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 来源/更多信息: http//us.php.net/manual/en/function.usort.php

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
}

Updated example with a little snippet using in memory database :) PS: the XSS protection in this example is not needed at all because I check the input as boolean value. 更新的示例在内存数据库中使用了一个小片段:) PS:完全不需要此示例中的XSS保护,因为我将输入检查为布尔值。 To see results in reverse order you specify order?desc 要以相反的顺序查看结果,请指定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. 首先,我有几个问题,你说你使用的是PHP5。 How do you retrieve your data(RDBMS)? 您如何检索数据(RDBMS)? If not, PHP5 has SQLite enabled by default . 如果没有, 默认情况下 PHP5已启用S​​QLite I think you should be using at least a RDBMS (SQLite/etc) to do the heavy lifting for you. 我认为您应该至少使用RDBMS (SQLite / etc)为您完成繁重的工作。

When you learn SQL you don't have to any sorting in PHP. 学习SQL时 ,不需要在PHP中进行任何排序。 I think this PDO tutorial while give you insides how to use SQL while doing it safely. 我认为这个PDO教程同时为您提供了如何在安全地使用SQL时使用SQL的内容。 SQL is vulnerable to SQL-injections but thanks to PDO's prepared statements you don't have to worry about that anymore. SQL容易受到SQL注入的影响,但是由于PDO的准备好的语句,您不必再为此担心。

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. 使用ORDER BY进行订购。 I would use a datatable to do the sorting client-side. 我会使用数据表来进行客户端的排序。 Also safes you to do work on the server(PHP). 还可以保证您在服务器上工作(PHP)。 You could for example look at YUI2's datatable . 例如,您可以查看YUI2的数据表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM