改进sql查询中的if语句

时间:2016-01-12 14:50:34

标签: php sql

我编写了一些工作正常的代码,但是非常冗长,并且想要了解如何提高效率。我正在运行不同的SQL查询,因为单个查询会返回太多结果;

$sql1 = "select blah blah blah";
$sql2 = "select blah blah blah";
$sql3 = "select blah blah blah";

$response1 = $client->executeSQLQuery(array("sql"=>$sql1));
$response2 = $client->executeSQLQuery(array("sql"=>$sql2));
$response3 = $client->executeSQLQuery(array("sql"=>$sql3));

if( is_array($response1->return->row) )
    {
        foreach($response1->return->row as $numbers)
            {
                echo $numbers->dnorpattern . "<br>";
        $count++;
                }
        }
else
        {
        echo $response1->return->row->dnorpattern . "<br>";
    $count++;
        }

if( is_array($response2->return->row) )
        {
        foreach($response2->return->row as $numbers)
                {
                echo $numbers->dnorpattern . "<br>";
                $count++;
                }
        }
else
        {
        echo $response2->return->row->dnorpattern . "<br>";
        $count++;
        }

if( is_array($response3->return->row) )
        {
        foreach($response3->return->row as $numbers)
                {
                echo $numbers->dnorpattern . "<br>";
                $count++;
                }
        }
else
        {
        echo $response3->return->row->dnorpattern . "<br>";
        $count++;
        }

所以,我想将if语句改为像这样的单个if语句;

if( is_array($response1->return->row) )
    {
        foreach($response1->return->row as $numbers)
            {
                echo $numbers->dnorpattern . "<br>";
        $count++;
                }
        }
else
        {
        echo $response1->return->row->dnorpattern . "<br>";
    $count++;
        }

$ sql和$ response的整数是可预测的,所以我应该可以使用for语句

for($x=1, $x<=3, $x++)
    {
    if( is_array($response[$x]->return->row) )
            {
            foreach($response[$x]->return->row as $numbers)
                    {
                    echo $numbers->dnorpattern . "<br>";
                $count++;
                    }
            }
            else
                {
                echo $response[$x]->return->row->dnorpattern . "<br>";
                $count++;
                }
    }

但是这不起作用,有人可以解释我如何正确地增加整数吗?

1 个答案:

答案 0 :(得分:1)

您可以使用花括号语法:

for($x=1; $x<=3; $x++)
{
    if( is_array(${'response' .$x}->return->row) )
    {
        foreach(${'response' .$x}->return->row as $numbers)
        {
            echo $numbers->dnorpattern . "<br>";
            $count++;
        }
    }
    else
    {
        echo ${'response' .$x}->return->row->dnorpattern . "<br>";
        $count++;
    }
}

或者将三个响应对象保存在一个数组中,并使用原始语法:

$response = [];
$response[1] = $client->executeSQLQuery(array("sql"=>$sql1));
$response[2] = $client->executeSQLQuery(array("sql"=>$sql2));
$response[3] = $client->executeSQLQuery(array("sql"=>$sql3));

虽然你可能只是编写一个更好的SQL查询并大大简化了事情