我的代码中有一些if语句。 e.g:
if($option[0]->posts == 1 && $option[0]->pages == 1){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND (post_type="page" OR post_type="post") ORDER BY post_title ASC', OBJECT );
}
if($option[0]->pages == 1 && $option[0]->posts == 0){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="page" ORDER BY post_title ASC', OBJECT );
}
if($option[0]->pages == 0 && $option[0]->posts == 1){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="post" ORDER BY post_title ASC', OBJECT );
}
上面代码的一些伪代码:
如果foo = 1且bar = 1 - >返回foo和bar
如果foo = 0且bar = 1 - >仅返回栏
如果foo = 1且bar = 0 - >只返回foo
如果foo = 0且bar = 0 - >返回错误
你看:
00
10
01
11
00
如果我插入另一个变量,我将获得更多机会,这真的很糟糕。因为如果陈述我会变得非常重要。
有人能告诉我另一个机会来获得相同的结果吗?
谢谢。
答案 0 :(得分:2)
我会这样做:
EntityFramework.SqlServer.dll
答案 1 :(得分:1)
请尝试以下代码:
$sub_query = $operator = '';
if($option[0]->posts == 1)
{
$sub_query = 'post_type="page"';
$operator = ' OR';
}
if($option[0]->pages == 1)
{
$sub_query .= $operator.' post_type="post"';
}
if(empty($sub_query))
{
return false;
}
else
{
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND ('.$sub_query.') ORDER BY post_title ASC', OBJECT );
}
答案 2 :(得分:0)
创建一个数组($ arr)并将键设置为“0,0”,并将值设置为“$ sql”; 你的代码将是这样的:
$tempKey = $option[0]->pages . "," . $option[0]->posts;
if(isset($arr[$tempKey]) {
$results = $wpdb->get_results($arr[$tempKey]);
}
因此,当您想要添加更多页面和帖子时,您将要做的就是更改arr。
答案 3 :(得分:0)
$types = [];
if ($option[0]->posts)
$types[] = '"post"';
if ($option[0]->pages)
$types[] = '"page"';
if (!$types)
return null;
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND (post_type IN ('. implode(',', $types) .')) ORDER BY post_title ASC', OBJECT );