如何将`if condition`转换为`switch`方法 [英] How to convert `if condition` to `switch` method
本文介绍了如何将`if condition`转换为`switch`方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果在开关
方法中<条件,如何写这个?
How can I write this if condition
in switch
method?
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(...));
}
编辑:
对不起,我想我之前没有说清楚,下面就是我想要的方式,
Sorry I think I didn't make it clear earlier, below is how I want to use it,
$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 = ?";
}
你可以看到我重复那里的条件 -
as you can see I repeated the condition there -
if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user' )
并且可能在某个时间点长。
and it may grow long at some point.
推荐答案
(借用上一个我认为产生这个问题的问题 - 快捷方式更新数据库中的表格行?
(Borrowing from a previous question which I believe spawned this one - 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
));
这篇关于如何将`if condition`转换为`switch`方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文