PHP if ifif其他基于数组

时间:2011-11-08 01:05:09

标签: php arrays if-statement

我的var_dump正在返回:

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

我在“radioinput”阵列上遇到问题。

如果它是“侧边栏左侧”我希望它回应:

<body class="sidebar-left">

如果它是“侧边栏 - 右边”我希望它回应:

<body class="sidebar-left">

如果它是“双边栏”,我希望它回应:

<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">';
}
?>

3 个答案:

答案 0 :(得分:3)

您对阵列的处理方式不正确。我假设数组将被称为$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">';
}

干杯:)

答案 1 :(得分:0)

改变这个:

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

对此:

// This assumes you named the array as $array, this was not mentioned in OP
if ($array['radioinput'] == 'sidebar-left') { 

答案 2 :(得分:0)

$class = $array['radioinput'] == 'sidebar-right' ? 'right' : 'left';
printf('<body class="sidebar-%s">', $class);