简体   繁体   English

如何从PHP foreach循环中排除隐藏字段

[英]How do I exclude hidden field from PHP foreach loop

I have a simple form that inserts data into a database using foreach($_POST as $key=>$value) I have a hidden field on the form 我有一个简单的表单,使用foreach将数据插入数据库($ _ POST作为$ key => $ value)我在表单上有一个隐藏字段

<input name="isset" type="hidden" value="true" />

And i use if(isset($_POST['isset'])) { 我使用if(isset($ _ POST ['isset'])){

I'm trying to work out how to exclude the hidden field from the loop ...? 我正试图找出如何从循环中排除隐藏字段......?

I've looked at this post but don't understand where i would use if (strpos($key, 'hdn_') == false) // proceed 我看过这篇文章,但不明白我会在哪里使用if(strpos($ key,'hdn_')== false)//继续

How to exclude <input type="hidden"> from a for each loop in PHP 如何从PHP中的每个循环中排除<input type =“hidden”>

any guidance would be appreciated.... 任何指导将不胜感激....

If you know the exact names of keys you want to exclude, array_diff_key is a convenient option: 如果您知道要排除的键的确切名称,则array_diff_key是一个方便的选项:

$keysToRemove = array('isset'); // you can add as many as you want
$values = array_diff_key($_POST, array_flip($keysToRemove));

foreach ($values as $k => $v) { ... }

However, since $values is intended to go into the database you should use a whitelist of allowed keys instead of a blacklist. 但是,由于$values旨在进入数据库,因此您应该使用允许密钥的白名单而不是黑名单。 You can do that with array_intersect_key : 您可以使用array_intersect_key执行此操作:

$keysToKeep = array('field1', 'field2', 'field3'); // as many as you want
$values = array_intersect_key($_POST, array_flip($keysToKeep));

foreach ($values as $k => $v) { ... }

Inside the foreach: 在foreach内:

foreach ($_POST as $key => $value) {
    if ($key != 'isset') {
        //code here
    }
}

(For what I got from your question) (对于我从你的问题得到的)

Or from your array, you can unset() the element with the 'isset' array key. 或者从数组中,您可以使用'isset'数组键unset()元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM