提问者:小点点

如何组合或简化多个语句


我有重复的语句,需要帮助来简化或组合语句,它们都有相似的值,范围从Jan-Dac和项目(本例中的sales change to Division category,sales change to 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个答案

匿名用户

我会做这样的事:

$months = [
   'jan',
   'dec',
   ...
];
$numberOfIterations = 32;

for ($i = 1 ; $i <= $numberOfIterations ; $i++) {
   if (isset($_POST["submit{$i}"])) {
      foreach ($months as $month) {
         $xml->ncvat->$month = $_POST[$month];
         file_put_contents("2020/data.xml", $xml->asXML());
      }
   }
}

您可以通过例如在表单中设置一个“隐藏”字段来更改“NCVAT”。 如:

<input type="hidden" name="type" value="ncvat">

后来呢:

$months = [
   'jan',
   'dec',
   ...
];
$numberOfIterations = 32;

for ($i = 1 ; $i <= $numberOfIterations ; $i++) {
   if (isset($_POST["submit{$i}"])) {
      $type = $_POST['type'];
      foreach ($months as $month) {
         $xml->$type->$month = $_POST[$month];
         file_put_contents("2020/data.xml", $xml->asXML());
      }
   }
}

匿名用户

通常当你有很多重复的任务时,循环是你最好的选择。 在这种情况下,我认为2个循环将解决您的问题。

//count of `submit` values to check for
$submission_count = 32;

//list of months
$months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

//loop for each `submit` value (e.g 1 through `$submission_count`)
for ($sub = 1; $sub <= $submission_count; $sub++) {
    
    //set up your `$item` (e.g "sales", "ncvat")
    switch($sub) {
        case 1:
            $item = 'sales';
            break;
        case 2:
        case 3:
        case 4:
        //etc
            $item = 'ncvat';
            break;
    }

    //check if submit value exists for current loop (e.g $_POST['submit1'])
    if(isset($_POST["submit{$sub}"])) {

        //loop each month
        foreach($months as $month) {

            //update xml for current month in current submission loop
            $xml->{$item}->{$month} = $_POST[$month];
            file_put_contents("2020/data.xml", $xml->asXML());
        }
    }
}