有没有办法缩短这段代码?它适用于树莓派控制面板。我将在稍后添加这些功能,但我现在的主要目标是缩短它。
<form action="" method="post">
<?php
if (!isset($_POST["submit"])) {
$lamp1 = "uit";
$lamp2 = "uit";
$lamp3 = "uit";
$lamp4 = "uit";
$lamp5 = "uit";
}
else
{
$lamp1 = $_POST['lamp1'];
$lamp2 = $_POST['lamp2'];
$lamp3 = $_POST['lamp3'];
$lamp4 = $_POST['lamp4'];
$lamp5 = $_POST['lamp5'];
if($_POST['submit'] == " Slaapkamer ")
{
if($_POST['lamp1'] == "uit")
{
$lamp1 = "aan";
}
else
{
$lamp1 = "uit";
}
}
else if($_POST['submit'] == " Badkamer ")
{
if($_POST['lamp2'] == "uit")
{
$lamp2 = "aan";
}
else
{
$lamp2 = "uit";
}
}
else if($_POST['submit'] == " Woonkamer ")
{
if($_POST['lamp3'] == "uit")
{
$lamp3 = "aan";
}
else
{
$lamp3 = "uit";
}
}
else if($_POST['submit'] == " Keuken ")
{
if($_POST['lamp4'] == "uit")
{
$lamp4 = "aan";
}
else
{
$lamp4 = "uit";
}
}
else if($_POST['submit'] == " WC ")
{
if($_POST['lamp5'] == "uit")
{
$lamp5 = "aan";
}
else
{
$lamp5 = "uit";
}
}
}
?>
<ul>
<li><input type="submit" name="submit" value=" Slaapkamer "></li>
<input type="hidden" name="lamp1" value=<?php echo $lamp1; ?>>
<li><?php echo 'Slaapkamer licht: '.$lamp1; ?></li>
<li><input type="submit" name="submit" value=" Badkamer "></li>
<input type="hidden" name="lamp2" value=<?php echo $lamp2; ?>>
<li><?php echo 'Badkamer licht: '.$lamp2; ?></li>
<li><input type="submit" name="submit" value=" Woonkamer "></li>
<input type="hidden" name="lamp3" value=<?php echo $lamp3; ?>>
<li><?php echo 'Woonkamer licht: '.$lamp3; ?></li>
<li><input type="submit" name="submit" value=" Keuken "></li>
<input type="hidden" name="lamp4" value=<?php echo $lamp4; ?>>
<li><?php echo 'Keuken licht: '.$lamp4; ?></li>
<li><input type="submit" name="submit" value=" WC "></li>
<input type="hidden" name="lamp5" value=<?php echo $lamp5; ?>>
<li><?php echo 'WC licht: '.$lamp5; ?></li>
</ul>
</form>
此代码将用于基于网络的应用程序来控制我的家。
答案 0 :(得分:0)
给你一个如何缩短事物的例子:
<?php
$kamers = [
'Slaapkamer'=>['lamp'=>1,'status'=>'uit'],
'Badkamer'=>['lamp'=>2,'status'=>'uit'],
'Woonkamer'=>['lamp'=>3,'status'=>'uit'],
'Keuken'=>['lamp'=>4,'status'=>'uit'],
'WC'=>['lamp'=>5,'status'=>'uit']
];
$htmlKamers = '';
$htmlKamers .= '<div>';
foreach($kamers as $kamer=>$data) {
$lightStatus = isset($_POST['lamp'.$data['lamp']]) && $_POST['lamp'.$data['lamp']] == 'uit' ? 'aan' : 'uit';
$elemChecked = $lightStatus === 'aan' ? 'checked': '';
$htmlKamers .= '<input type="checkbox" name="lamp'.$data['lamp'].'" value="'.$lightStatus.'" '.$elemChecked.'> '.$kamer.' ('.$lightStatus.')<br/>';
}
$htmlKamers .= '</div>';
?>
<form method="post">
<input type="hidden" name="lamp1" value="aan">
<?php echo $htmlKamers;?>
<button type="submit">Send</button>
</form>