簡體   English   中英

PHP 數組和 htmlentities

[英]PHP array and htmlentities

$_POST=

Array ( [0] => aaa@gmail.com [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 s 與$_POST相同,則將其留空。




2019 年 11 月 18 日更新


事實上,如果您正在處理關聯數組,例如 _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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM