使用数组简化if else语句

时间:2013-02-19 14:54:10

标签: php arrays wordpress if-statement

我有不同样式表选择的wordpress主题设置,使用前端的if else语句设置。

我的wordpress设置可能包含以下值池中的一个值

red ,green, blue, yellow, white, pink, black, grey ,silver or purple

我的模板:

<link href="<?php bloginfo("template_url"); ?>/style.css" rel="stylesheet" media="all" />

<?php if (get_option('my_style') == "red"  : ?>
<link href="<?php bloginfo("template_url"); ?>/css/red.css" rel="stylesheet" media="all" />
<?php endif; ?>

<?php if (get_option('my_style') == "green"  : ?>
<link href="<?php bloginfo("template_url"); ?>/css/green.css" rel="stylesheet" media="all" />
<?php endif; ?>

<?php if (get_option('my_style') == "blue"  : ?>
<link href="<?php bloginfo("template_url"); ?>/css/blue.css" rel="stylesheet" media="all" />
<?php endif; ?>

<?php if (get_option('my_style') == "yellow"  : ?>
<link href="<?php bloginfo("template_url"); ?>/css/yellow.css" rel="stylesheet" media="all" />
<?php endif; ?>
.
.
.
.
.
<?php if (get_option('my_style') == "purple"  : ?>
<link href="<?php bloginfo("template_url"); ?>/css/purple.css" rel="stylesheet" media="all" />
<?php endif; ?>

通过这种方式,我可以根据需要获得特定的样式表。但是如果选项池中有更多值,则此php代码会变得很长。那么有没有办法使用数组来缩短它?

4 个答案:

答案 0 :(得分:3)

可能是你可以把它减少到

<link href="<?php bloginfo("template_url"); ?>/css/<?php echo get_option('my_style'); ?>.css" rel="stylesheet" media="all" />

如果函数get_option返回与css文件名相同的字符串,我认为你不需要数组。

答案 1 :(得分:1)

此选项:

<?php
$arraystyle=array("red", "green", "blue", "yellow", "white", "pink", "black", "grey", "silver", "purple");

$val=get_option('my_style');
if(!in_array($val, $arraystyle)){
    echo "Style not found";
    return false;
}
?>

<link href="<?php bloginfo("template_url"); ?>/css/<?php echo $arraystyle[$val];?>.css" rel="stylesheet" media="all" />

答案 2 :(得分:0)

这里没有真正需要使用数组。您正在根据特定值更改您所包含的CSS文件。

我认为你要找的是一个switch case命令。以下是您可以使用它的一个简单示例 -

<?php

$my_style = get_option('my_style');
switch($my_style){
 case "red":
   echo '<link href="'. bloginfo("template_url"). '/css/red.css" rel="stylesheet" media="all" />';
 break;
 case "green":
   echo '<link href="'. bloginfo("template_url"). '/css/green.css" rel="stylesheet" media="all" />';
 break;
 default :
   echo '<link href="'. bloginfo("template_url"). '/css/default.css" rel="stylesheet" media="all" />';
 break;
}

?>

使用此方法,您可以为每个my_style选项添加多个更改。请注意使用默认情况来处理任何意外值......

参考 -

答案 3 :(得分:0)

<?php
$my_styles = array(
    'red',
    'green',
    'blue',
    'yellow',
    'white',
    'pink',
    'black',
    'grey',
    'silver'
);
?>
<?php if(in_array($my_style = get_option('my_style'),$my_styles)) : ?>
    <link href="<?php echo bloginfo("template_url")."/css/{$my_style}.css"; ?>" rel="stylesheet" media="all" /> 
<?php endif; ?>

您可以使用$ my_styles填充变量以及所有可用的样式,无论是来自数据库还是其他..

相关问题