PHP: do an ORDER BY using external data?

五迷三道 提交于 2019-12-02 02:22:18

问题


Ahoy all! Long story short with this one if you don't mind lending a hand to this novice PHPer. :)

I have a database field called "Categories" that has this stored:

Fruit, People, Place, Animals, Landscape

I also have a separate table in the DB that has items with these category names in the fields for each item. Right now, the script (i am trying to fork it a bit) uses:

SELECT DISTINCT(type), type FROM the_categories ORDER BY type ASC 

in order to display a list of all categories available. Simple enough right?

Welllllll..... I don't want to sort by ASC, I want to sort by the list of items in the first Categories field I mentioned. Whatever order those are in is the order I want to display the "types" above.

Obviously I will have to do an explode on the commas, and maybe give them a 1 to whatever order....but even then.... how do I do an "orderby" using data stored in another folder?

Is this even possible? lol Thanks again!


回答1:


... ORDER BY FIELD(type,"Fruit","People","Place","Animals","Landscape")

http://www.cfdan.com/posts/Handy_MySQL_-_ORDER_BY_FIELD.cfm




回答2:


And just so future onlookers have it .... here is the explode code

$query2 = mysql_query("SELECT * FROM categorytable");
        while($row = mysql_fetch_array($query2)){
            $categories = html_entity_decode($row['categories']);
            $thelist = explode(',', $categories);

        foreach($thelist as $order){
            if(trim($order) != ''){
                $order = trim($order);
                $order = ", '".$order."'";
                $theorder .= $order;
            }
        }

and then for the query, just put in the the order variable

SELECT DISTINCT(type), type FROM the_categories ORDER BY FIELD(type" . $theorder .")")


来源:https://stackoverflow.com/questions/8721047/php-do-an-order-by-using-external-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!