我有一个使用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
}
if
条件嵌套在foreach
循环中的输入变量回显(第47行的回显&#39;)按照我的预期打印出来(输入到表单页面的值&# 39; s输入字段):
(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 -
然后相同的数组中的 key-val 对紧跟在foreach
循环中的紧跟在第52行的回声&#39; d之后发生任何进一步的变量处理,打印出每个键的空值:
(52) status:
(52) discoverDate:
(52) resolveDate:
(52) ticketIssued:
(52) eqptSystem:
(52) alarmCode:
(52) troubleDescription:
(52) troubleshootingSteps:
(52) resolveActivities:
(52) notes:
不知何故,阵列的关键值在分配后才为零,我无法弄清楚如何或为什么。任何人都可以看到明显的原因吗?
答案 0 :(得分:1)
$val = $_SESSION[ $key ] = sanitizeText( $_POST[ $key ] );
行不会更改$troubleInsertInputVarsArr
数组,因为$val
是数组元素值的副本,而不是引用。
更改foreach,以便$ val为参考。
foreach ( $troubleInsertInputVarsArr as $key => &$val ) {
答案 1 :(得分: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 . ' ';
}
}