如何缩短多个if语句的代码?

时间:2015-11-20 11:49:33

标签: php

我有一段时间在考虑这件事。我使用了很多if语句,有时候我有很多。我知道我可以使用switch来缩短代码。有没有其他方法来缩短它们?

假设我们有这个例子:

$all_conditions = '';

        if($post_status != ""){
            $conditions[] = "posts.post_status = '".$post_status."'";
        }
        if($post_type != ""){
            $conditions[] = "posts.post_type = '".$post_type."'";
        }
        if($meta_key != ""){
            $conditions[] = "postmeta.meta_key = '".$meta_key."'";
        }
        if($meta_value != ""){
            $conditions[] = "postmeta.meta_value = '".$meta_value."'";
        }
        if($date_begin != "" && $date_end != ""){
            $conditions[] = "( posts.post_date BETWEEN '".$date_begin."' AND '".$date_end."' )";
        }
        if(count($conditions)>0){
            $all_conditions = implode(" AND ",$conditions);
        }
        if($all_conditions != ""){
            $all_conditions = "WHERE ".$all_conditions;
        }

如果不重复所有这些,我该怎么办?

3 个答案:

答案 0 :(得分:1)

试试这个:

<?php
$all_conditions = '';
$checkArr = array('post_status' =>  'posts.post_status',
                  'post_type'   =>  'posts.post_type',
                  'meta_key'    =>  'postmeta.meta_key',
                  'meta_value'  =>  'postmeta.meta_value');
foreach ($checkArr AS $key => $val) {
    if (${$key} != '') {
        $conditions[] = "$val = '${$key}'";
    }
}
if($date_begin != "" && $date_end != ""){
    $conditions[] = "( posts.post_date BETWEEN '".$date_begin."' AND '".$date_end."' )";
}
if(count($conditions)>0){
    $all_conditions = "WHERE ".implode(" AND ",$conditions);
}  ?>

答案 1 :(得分:0)

我最好的猜测是你通过$post_status = $_POST['status']方式检索$ post_status,在这种情况下你可以像这样缩短它(其中一种方法):

$all_conditions = '';    
$mandatoryFields = array( 'status', 'type', 'key', 'value' );

foreach ( $mandatoryFields as $mandatoryField ) {
    if ( $_POST[$mandatoryField] != '' ) {
        $conditions[] = 'posts.`post_' . $mandatoryField  . '` = "'.$_POST[$mandatoryField].'"';
    }
}

然后去添加开始日期和结束日期,并从那里获取代码。

答案 2 :(得分:0)

无技术答案

我有时也使用类似的检查,我认为它不应该包含foreach语句,因为这会降低代码的易读性和可维护性。但是,如果您有超过10个类似的条件,它确实有意义。但是你可以通过不将条件置于一个块中来使其更具可读性,并且可能添加一些结构和&amp;&amp;注释:

// check fields
if($post_status != "") $conditions[] = "posts.post_status = '".$post_status."'";
if($post_type != "") $conditions[] = "posts.post_type = '".$post_type."'";
if($meta_key != "") $conditions[] = "postmeta.meta_key = '".$meta_key."'";
if($meta_value != "") $conditions[] = "postmeta.meta_value = '".$meta_value."'";

// check dates
if($date_begin != "" && $date_end != "") $conditions[] = "( posts.post_date BETWEEN '".$date_begin."' AND '".$date_end."' )";

// any conditions present?
if(count($conditions)>0) {
    $all_conditions = implode(" AND ",$conditions);
    $all_conditions = "WHERE ".$all_conditions;
}
else $all_conditions = '';

我还将字符串连接放在count($conditions)>0内,因此您无需检查两次。