php - 如何合并或简化多个语句
问题描述
我有重复的语句,需要帮助来简化或合并语句 它们都有相似的值,范围从 1 月到 12 月,并且项目(在本示例中,销售额更改为不同的类别,销售额更改为 ncvat)更改了 32 个不同的类别,每个组都有一个不同的提交值
if(isset($_POST['submit1'])){
$xml->sales->jan = $_POST['jan'];
file_put_contents("2020/data.xml", $xml->asXML());
}
...................................
...................................
if(isset($_POST['submit1'])){
$xml->sales->dec = $_POST['dec'];
file_put_contents("2020/data.xml", $xml->asXML());
}
然后我有
if(isset($_POST['submit2'])){
$xml->ncvat->jan = $_POST['jan'];
file_put_contents("2020/data.xml", $xml->asXML());
}
...................................
...................................
if(isset($_POST['submit2'])){
$xml->ncvat->dec = $_POST['dec'];
file_put_contents("2020/data.xml", $xml->asXML());
}
因此它进行了 32 种不同的表单提交动作
解决方案
通常,当您有很多重复性任务时,循环是您的最佳选择。在这种情况下,我认为 2 个循环将解决您的问题。
//list of "categories". This also dictates how many outer-loops there will be.
//Duplicates categories are allowed if needed.
$types = [
'sales',
'ncvat',
//...etc
];
//list of months
$months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
//loop each `$types`, and use `$key + 1` as an indicator for which "submit value" you are processing
foreach($types as $key => $type)
//to start $sub at `1` instead of `0`
$submit_value = $key + 1;
//check if submit value exists for current loop (e.g $_POST['submit1'])
if(isset($_POST["submit{$submit_value}"])) {
//loop each month
foreach($months as $month) {
//update xml for current month in current submission loop
$xml->{$type}->{$month} = $_POST[$month];
}
}
}
//submit all changes at once instead of overwriting on each inner-loop.
file_put_contents("2020/data.xml", $xml->asXML());