在PHP中重构if语句或为if语句提供其他解决方案(不要切换大小写)



我的代码中有一些if语句。例句:

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 and bar = 1 ->返回foo and bar

如果foo = 0 and bar = 1 ->只返回bar

if foo = 1 and bar = 0 ->只返回foo

if foo = 0 and bar = 0 ->返回false

你看:

0010

01

11

00

如果我插入另一个变量,我将得到更多的机会,这真的很糟糕。因为我将得到非常大的if语句

谁能告诉我另一个达到同样结果的机会?

谢谢。

我想这样做:

$sql_condition = '( 1=2 '; // one fake-condition, just to make it possible to start with 'OR' later
foreach($option[0] as $key => $value) {  // iterate through all possible conditions
    if($value===1) { // maybe exclude $keys that should not be used here
        $sql_condition.=' OR post_type="'.$key.'"';
    }
}
$sql_condition.=')';
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND '.$sql_condition.' ORDER BY post_title ASC', OBJECT );

请尝试此代码:

$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 );   
}     

创建一个数组($arr),并设置键为"0,0",值为"$sql";你的代码会像这样:

$tempKey = $option[0]->pages . "," . $option[0]->posts;
if(isset($arr[$tempKey]) {
     $results = $wpdb->get_results($arr[$tempKey]); 
}

所以当你想添加更多的页面和帖子时,你所要做的就是改变arr

$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 ); 

最新更新