dongmiao260399 2012-05-04 22:20
浏览 9
已采纳

PHP数组排序方式不同

I export from MYSQL db different info that I put inside an array:

$info=array(
(ID,CALORIES,PROTEIN,CARBOS,FIBER),
...
);
ex: (1,270,24,12,5),(2,280,2,42,10),...

Then, further down the script, I need to get the IDs of the 3 products with the highest calories, of the 6 products with the highest result of 2xPROTEIN+3xCARBOS, etc for 5 charts.

How can I do such a sorting of the array to fill my different tables?

The function sort() only seems to work for a single-dimensioned array (if it works for my case, I don't know what would be the syntax). It also doesn't seem to work for my more advanced sortings (2*x+3*y)...

  • 写回答

4条回答 默认 最新

  • dongyuxin5353 2012-05-04 22:25
    关注

    Even tho it is not exactly what you are asking, I would highly suggest you preparing your tables in mysql (using all formulas to sort, etc.). Mysql's main job is do various selections and sorting, I would leave the work for it. Moreover, advanced sorting in mysql is way easier than thinking of algorithms or functions in php :)

    SELECT * FROM `products`
    ORDER BY (2*PROTEIN+3*CARBOS) DESC
    

    Easy as that and no headaches. Apply LIMIT 3 at the end to get the top 3. Update

    SELECT * FROM `products`
    

    to your more advanced query. If having difficulties in code you may try to wrap it up as a subquery as this:

    SELECT * FROM (SELECT * FROM `products` WHERE `type`='fruit' LIMIT 6) a
    ORDER BY (2*PROTEIN+3*CARBOS) DESC LIMIT 3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口