如何将`if condition`转换为`switch`方法

时间:2011-08-02 02:13:18

标签: php if-statement switch-statement

如何在if condition方法中撰写此switch

if( $k != 'pg_id' && $k != 'pg_tag' && $k != 'pg_user' )
{
     $result = $connection->run_query($sql,array(...));
}

......吗?

switch($k)
{
case 'pg_id': false;
case 'pg_tag': false;
case 'pg_user': false;
default:
   $result = $connection->run_query($sql,array(...));

}

修改

对不起,我想我之前没说清楚,下面就是我想用它的方式,

$editable_fields = array(
    'pg_id',
    'pg_url',
    'pg_title',
    'pg_subtitle',
    'pg_description',
    'pg_introduction',
    'pg_content_1',
    'pg_content_2',
    'pg_content_3',
    'pg_content_4',
    'pg_backdate',
    'pg_highlight',
    'pg_hide',
    'pg_cat_id',
    'ps_cat_id',
    'parent_id',
    'tmp_id',
    'usr_id'
);

$sql_pattern = array();

foreach( $editable_fields as $key )
{
    if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user'  ) $sql_pattern[] = "$key = ?";
}

你可以看到我在那里重复了这个条件 -

if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user'  )

并且它可能在某个时候变长。

3 个答案:

答案 0 :(得分:2)

使用break阻止跟进下一个案例:

switch($k)
{
case 'pg_id':
case 'pg_tag':
case 'pg_user':
  // any match triggers this block; break causes no-op
  break;
default:
  $result = $connection->run_query($sql,array(...));
}

我不知道你为什么要为此使用switch语句。

如果是为了便于阅读,可以尝试这样做:

if($k != 'pg_id' &&
   $k != 'pg_tag' &&
   $k != 'pg_user')
{
  $result = $connection->run_query($sql,array(...));
}

答案 1 :(得分:0)

切换条件可能更快(跳转表)并且更容易阅读。你可以跳过休息时间;如果条件的结果相同,并且改进的语法是在每个条件中使用花括号:

switch ($k)
{
 case 'pg_id':
 case 'pg_tag':
 case 'pg_user': {
 break;
 }
 default: {
   $result = $connection->run_query($sql,array(...));
 }
}

答案 2 :(得分:0)

(借用上一个我相信产生这个问题的问题 - A short-cut to update a table row in the database?

$editable_fields = array(
  'pg_url' ,
  'pg_title' ,
  ...
);
/* These are the fields we will use the values of to match the tuple in the db */
$where_fields = array(
  'pg_id' ,
  'pg_tag' ,
  'pg_user' ,
  ...
);

$form_values = array();
$sql_pattern = array();
foreach( $editable_fields as $k ){
  if( $k != 'pg_id'
      && isset( $_POST[$k] ) ){
    $form_values[$k] = $_POST[$k];
    // NOTE: You could use a variant on your above code here, like so
    // $form_values[$k] = set_variable( $_POST , $k );
    $sql_pattern[] = "$k = ?";
  }
}
$where_values = array();
$where_pattern = array();
foreach( $where_fields as $k ){
  if( isset( $_POST[$k] ) ){
    $where_values[$k] = $_POST[$k];
    // NOTE: You could use a variant on your above code here, like so
    // $form_values[$k] = set_variable( $_POST , $k );
    $where_pattern[] = "$k = ?";
  }
}

$sql_pattern = 'UPDATE root_pages SET '.implode( ' , ' , $sql_pattern ).' WHERE '.implode( ' , ' , $where_pattern );

# use the instantiated db connection object from the init.php, to process the query
$result = $connection->run_query($sql_pattern,array_merge(
    $form_values ,
    $where_values
    ));