简体   繁体   English

在php中实时排序查询结果

[英]Live sort query results in php

I have a query which goes through the table and outputs the data like this: 我有一个查询通过表并输出如下数据:

Query 询问

$query = mysql_query("SELECT * FROM `products`");
while($row = mysql_fetch_assoc($query)){
    $array[] = $row;
}

foreach ($array as $key) {
    $name[]    = $key['name'];
    $desc[]    = $key['desc'];
    $cost[]    = $key['price'];
}

$c = 0;
while($c<(count($array))){
    echo 'Name: '.$name[$c].'<br>';
    echo 'Desc: '.$desc[$c].'<br>';
    echo 'Price: '.$cost[$c].'<br><br>';
    $c++;
}

Results 结果

Name: xyz1 名称:xyz1
Desc: asdxsadasda 描述:asdxsadasda
Price: 999 价格:999

Name: xyz2 名称:xyz2
Desc: asdxsadasda 描述:asdxsadasda
Price: 333 价格:333

Name: xyz3 名称:xyz3
Desc: asdxsadasda 描述:asdxsadasda
Price: 666 价格:666

I want to be able to sort these results based on the price of each item. 我希望能够根据每个项目的价格对这些结果进行排序。
Can I output the result in a jSON file and use that to sort the results (live-without loading the page)? 我可以将结果输出到jSON文件中并使用它来对结果进行排序(实时 - 不加载页面)?

Could you suggest me a better way to sort the results without having to load the page? 您是否可以建议我更好地对结果进行排序而无需加载页面?

$query = mysql_query("SELECT * FROM `products` WHERE `category` order by products.price, products.name");

您可以选择按ASC或DESC排序

If you MUST sort the array in PHP, after you got the query result, use the array_multisort function in PHP ( http://www.php.net/manual/en/function.array-multisort.php ) 如果必须在PHP中对数组进行排序,在获得查询结果后,请使用PHP中的array_multisort函数( http://www.php.net/manual/en/function.array-multisort.php

However, if your life does not depend on sorting in PHP, sort at the source in your SQL (the way God intended it to be) it's going to be much much faster and it will take the load off the web server. 但是,如果你的生活不依赖于PHP中的排序,那么在SQL中的源(按照上帝的意图)进行排序,它将会快得多,并且会减轻Web服务器的负担。

Hope this helps. 希望这可以帮助。

SELECT * FROM `products` order by price, name

此外,您不需要foreach,因为您可以在while循环中进行阵列设置。

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

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