如何将“if条件”转换为“switch”方法
如何在 switch
方法中编写这个 if 条件
?
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' )
它可能会在某个时候变得很长。
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(...));
}
to...?
switch($k)
{
case 'pg_id': false;
case 'pg_tag': false;
case 'pg_user': false;
default:
$result = $connection->run_query($sql,array(...));
}
EDIT:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
break
来防止继续执行下一种情况:但我不确定为什么要为此使用 switch 语句。
如果为了可读性,你可以尝试这样做:
Use
break
to prevent follow through to next case:I'm not sure why you want to use a switch statement for this though.
If it's for readability, you could try this instead:
(借用上一个问题,我相信这个问题催生了这个问题 - 更新数据库中表行的快捷方式?)
(Borrowing from a previous question which I believe spawned this one - A short-cut to update a table row in the database?)
切换条件可能会更快(跳转表)并且更容易阅读。你可以跳过休息时间;如果条件的结果相同,并且改进的语法是在每个条件内使用花括号:
A switch condition is likely to be faster (jump table) and a bit easier to read. You can skip the break; if the result of the condition is the same and an improved syntax is to use curly braces inside each condition: