PHP数组和htmlentities

问题描述 投票:0回答:1
$_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周围。你能帮我么?我已经坚持了几个小时。

php arrays key entities
1个回答
1
投票

您做错了这种方式。尝试-->

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])

© www.soinside.com 2019 - 2024. All rights reserved.