PHP if else基于数组


PHP if elseif else based on array

我的var_dump返回这个:

array(5) { 
    ["radioinput"]=> string(12) "sidebar-left" 
    ["option1"]=> int(0) 
    ["sometext"]=> string(0) "" 
    ["selectinput"]=> NULL 
    ["sometextarea"]=> string(0) "" 
}

我在"radioinput"数组上有问题。

如果是"sidebar-left"我想让它回显:

<body class="sidebar-left">

如果是"sidebar-right"我想让它回显:

<body class="sidebar-left">

如果是"two-sidebars"我想让它回显:

<body class="two-sidebars">

如果它是空的,我希望它回显:

<body class="sidebar-left">

我的问题是,我怎么能让我的代码做到这一点?

<?php 
if (radioinput('sidebar-left')) { 
    echo '<body class="sidebar-left">';
} elseif (radioinput('sidebar-right')) {
    echo '<body class="sidebar-right">';
} elseif (radioinput('two-sidebars')) {
    echo '<body class="two-sidebars">';
} else {
    echo '<body class="sidebar-left">';
}
?>

您对数组的寻址方式不正确。我假设数组将被称为$data

或将$data替换为var_dump(...)

然后,你的代码看起来像:
if ($data['radioinput'] == "sidebar-left"){
   echo '<body class="sidebar-left">';
}elseif ($data['radioinput'] == "sidebar-right"){
   echo '<body class="sidebar-right">';
}else{
   //otherwise
}

编辑:你甚至可以简化为:

if ($data['radioinput'] == "sidebar-right"){
   echo '<body class="sidebar-right">';
}else{
    echo '<body class="sidebar-left">';
}

欢呼:)

修改如下:

if (radioinput('sidebar-left')) { 

:

// This assumes you named the array as $array, this was not mentioned in OP
if ($array['radioinput'] == 'sidebar-left') { 
$class = $array['radioinput'] == 'sidebar-right' ? 'right' : 'left';
printf('<body class="sidebar-%s">', $class);