phpmysqlsortingsql-order-by

Sort MySQL query data by calculated values


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 (2x+3y)...


Solution

  • 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