gpt4 book ai didi

php - 缩短代码、ORDER BY 和 SWITCH

转载 作者:行者123 更新时间:2023-11-29 13:22:29 25 4
gpt4 key购买 nike

你能帮我缩短代码吗?要点是,我想根据给定的 $T 以不同的顺序从数据库中获取数据。任何想法?

public function rewriteQuery($T){

switch ($T) {

case 0:
$query="SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD(id,1,2,3,4,5,6)";
break;
case 1:
$query="SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD(id,2,3,4,5,6,1)";
break;
case 2:
$query="SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD(id,3,4,5,6,1,2)";
break;
case 3:
$query="SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD(id,4,5,6,1,2,3)";
break;
case 4:
$query="SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD(id,5,6,1,2,3,4)";
break;
default:
$query="SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD(id,6,1,2,3,4,5)";
break;

}

return $query;

}

最佳答案

缩短此过程的一种方法是创建一个返回order by字段的数组。

类似这样的事情:

$order_by_array = array(
0 => "(id,1,2,3,4,5,6)",
1 => "(id,2,3,4,5,6,1)",
2 => "(id,3,4,5,6,1,2)",
3 => "(id,4,5,6,1,2,3)",
4 => "(id,5,6,1,2,3,4)"
);

然后你的rewriteQuery($T)函数可以重写为:

public function rewriteQuery($T){
$order_by = "(id,6,1,2,3,4,5)"; // Default
if (array_key_exists($T, $order_by_array)) {
$order_by = $order_by_array[$T];
}

$query = "SELECT id, title FROM kshome WHERE del=0 AND active=1 ORDER BY FIELD{$order_by}";
...
}

关于php - 缩短代码、ORDER BY 和 SWITCH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com