$_POST=
Array ( [0] => [email protected] [1] => bbb [2] => ccc [3] => ddd [4] => eee [5] => fff [6] => ggg [7] => hhh [8] => iii [9] => jjj [10] => 31 [11] => k )
foreach($_POST as $key => $val){
for ($key = 0; $key <= 9;$key++){
$_POST2[$val] = htmlentities($_POST[$val]);
}
}
}
这是我的代码,我想做的是我想将$_POST
数组拆分为$key
和$val
。然后我想告诉程序,当$key
上升1
时,将htmlentities()
放在$val
周围。你能帮我么?我已经坚持了几个小时。
您做错了这种方式。尝试-->
foreach($_POST as $key => $val){ $_POST2[] = htmlentities([$val]); }
不需要该
for
循环。foreach
将包装所有值。如果您希望key
与$_POST
相同,则将其留空。
更新18.11.2019
实际上,如果您正在处理诸如_POST之类的关联数组(与索引数组相反),在其中您要处理具有名称而不是数字的键,那么您必须编写如下代码:
// this is the classic orthodox syntax foreach($_POST as $key => $val){ $_POST[$key] = htmlentities($val); }
[如果想像我朋友在上侧建议的那样省略
$key
,它将起作用,但是最终您将得到一个组合数组,该数组同时具有关联性和索引性(使用双内存,极大地降低了您的速度脚本)。更重要的是,它不会更改关联部分,它将产生并附加已被htmlentities
修改的索引数组。
// appends a indexed array foreach($_POST as $key => $val){ $_POST[] = htmlentities($val); } // The & in front of $val permits me to modify the value of $val // inside foreach, without appending a indexed array: foreach($_POST as &$val){ $val = htmlentities($val); }
如果使用索引数组,则始终可以忽略
$key
,但也请注意,它是htmlentities($val)
而不是htmlentities([$val])
。