数组键值在分配后立即清空/归零

fak*_*ted 7 php

我有一个表单,使用PHP设置页面的输入字段值,如:

// create and fill inputVarsArr with keys that have empty vals
$troubleInsertInputVarsArr = array_fill_keys(array('status', 'discoverDate', 'resolveDate', 'ticketIssued', 'eqptSystem', 'alarmCode', 'troubleDescription', 'troubleshootingSteps', 'resolveActivities', 'notes'), '');

if (isset ($_POST['insert'])) { // update DB site details 
    foreach ($troubleInsertInputVarsArr as $key => $val) {
        if ($key !== 'discoverDate' && $key !== 'resolveDate') { //deal with dates separately below
            $val = $_SESSION[$key] = sanitizeText($_POST[$key]);
            echo '<br>(' . __LINE__ . ') ' . $key . ': ' . $val . ' ';
        } // close IF ; line 47 echo
    } // close FOREACH

    foreach ($troubleInsertInputVarsArr as $key => $val) {
        echo '<br>(' . __LINE__ . ') ' . $key . ': ' . $val . ' ';
    } // close FOREACH // line 52 echo
}
Run Code Online (Sandbox Code Playgroud)

if嵌套在foreach循环中的条件中回显的输入变量(第47行的echo')按照我的预期打印出来(输入到表单页面输入字段的值):

(47) status: Outstanding
(47) ticketIssued: no
(47) eqptSystem: Tower Lights
(47) alarmCode: Visual
(47) troubleDescription: - no description yet -
(47) troubleshootingSteps: - no steps yet taken -
(47) resolveActivities: - no activities yet decided -
(47) notes: - no notes -
Run Code Online (Sandbox Code Playgroud)

但是,相同数组中的相同键 - 值对在foreach紧接着的循环中回显(在第52行上回显),而没有发生任何进一步的变量处理,为每个键打印出空值:

(52) status:
(52) discoverDate:
(52) resolveDate:
(52) ticketIssued:
(52) eqptSystem:
(52) alarmCode:
(52) troubleDescription:
(52) troubleshootingSteps:
(52) resolveActivities:
(52) notes: 
Run Code Online (Sandbox Code Playgroud)

不知何故,数组的键值在分配后立即归零,我无法弄清楚如何或为什么.任何人都可以看到为什么会出现这种情况的明显原因?

del*_*8uk 1

您永远不会为 $troubleInsertInputVarsArr 分配值,而只能为键分配值。你可以试试这个:

   foreach ( $troubleInsertInputVarsArr as $key => $val ) {
      $troubleInsertInputVarsArr[$key] = sanitizeText( $_POST[ $key ]); 
      if ( $key !== 'discoverDate' && $key !== 'resolveDate' ) { 
          $val = $_SESSION[ $key ] = sanitizeText( $_POST[ $key ] );
          echo '<br>(' . __LINE__ . ') ' . $key . ': ' . $val . ' ';
      } 
    }
Run Code Online (Sandbox Code Playgroud)