我如何改进此代码,以便我不会一遍又一遍地重复相同的功能?我正在努力为此创建一个函数,因为变量名需要专门设置,以便稍后在代码中使用。
这里的代码......
if (in_array("knownValue", $array)) {
$variableA = true;
} else {
$variableA = false;
}
if (in_array("knownValue", $array)) {
$variableB = true;
} else {
$variableB = false;
}
if (in_array("knownValue", $array)) {
$variableC = true;
} else {
$variableC = false;
}
if (in_array("knownValue", $array)) {
$variableD = true;
} else {
$variableD = false;
}
稍后在代码中使用...
if ($variableA) {
//do stuff...
} else {
//do other stuff...
}
if ($variableB) {
//do stuff...
} else {
//do other stuff...
}
etc...
编辑 -
谢谢,我知道我只需要睡觉吧!管理将代码浓缩为
<select class='selectpicker width100 updateAbilities' name='staffAbliities[]' multiple>";
function renderOption($ability, $title, $array) {
if (in_array($ability, $array)) {
echo "
<option data-content='<img src='images/abilities/$ability.png'> $title' value='$ability' selected>
$title
</option>";
} else {
echo "
<option data-content='<img src='images/abilities/$ability.png'> $title' value='$ability'>
$title
</option>";
}
}
renderOption("ops", "Operations Manager", $abilities);
renderOption("guide_manager", "Guide Manager", $abilities);
renderOption("senior_guide", "Senior Guide", $abilities);
renderOption("guide", "Guide", $abilities);
renderOption("trainee_guide", "Trainee Guide", $abilities);
renderOption("big_bus", "Full PCV License", $abilities);
renderOption("small_bus", "Small PCV License", $abilities);
renderOption("wfr", "Wilderness First Responder", $abilities);
renderOption("ice_climber", "Ice Climber", $abilities);
echo "
</select>
答案 0 :(得分:0)
我认为首先检查变量是不必要的。 没有第一部分,您的代码将正常工作。你可以试试这个
$yourKeyForCheck = 'knownValue'
if (array_value($yourKeyForCheck, $array)) {
//do stuff
} else {
//do other stuff...
}
编辑: 我认为这是更优雅的决定
$aOptions = [
[ 'name' => 'ops',
'title' => 'Operations Manager',
'abilities' => $abilities,
],
[ 'name' => 'guide_manager',
'title' => 'Guide Manager',
'abilities' => $abilities,
],
[ 'name' => 'senior_guide',
'title' => 'Senior Guide',
'abilities' => $abilities,
],
[ 'name' => 'guide',
'title' => 'Guider',
'abilities' => $abilities,
],
[ 'name' => 'ops',
'title' => 'Operations Manager',
'abilities' => $abilities,
],
];
<select class='selectpicker width100 updateAbilities' name='staffAbliities[]' multiple>";
<?php forech($aOptions as $aOption) { ?>
<option
data-content='<img src='images/abilities/$ability.png'>
<?php echo $aOption['title']?>';
value='<?php echo $aOption['abilities']; ?>'
<?php echo in_array($ability, $array)? selected : '' ?>
$title
</option>";
<?php } ?>
</select>