2014-03-28 54 views
0

我很困惑,这是什么,以及如何在表单处理中使用它。它是否只删除不在$ expected []中的不需要的$ _POST条目?我还应该使用$ _POST ['carModel']来获得价值吗?或者可能有更好的方法?PHP我该如何使用它?

<?php 
$expected = array('carModel', 'year', 'bodyStyle'); 
foreach($expected AS $key) { 
    if (!empty($_POST[ $key ])) { 
     ${$key} = $_POST[ $key ]; 
    } 
    else 
    { 
     ${$key} = NULL; 
    } 
} 
?> 
+0

你为什么要这么做? –

+0

这是一个冗长的“提取物”,仅限于本地化一些已知的输入值。 – mario

+0

你想要完成什么? – YouSer

回答

0

权,伪代码$ {$变量}是一个新变量的创建,又名:

//$_POST['test'],$_POST['future'] 
foreach($_POST AS $key) { 
    ${$key} = $_POST[ $key ]; 
} 

你分配$ _ POST [$关键]到$ test,如$ test = $ _POST [$ key]; echo $ future; //具有相同的值$ _POST ['future']

现在,您可以跳过使用$ _POST来使用$ test,后期中的所有数组键都应该分配在一个由键的名称调用的变量中;

在你的例子中,$例外的工作就像一个过滤器,只分配这个数组中的变量。您应该使用过滤器来清洁$ _POST,然后分配给$ {$}。

+0

不确定$ {$ key}在做什么。我看到它现在创建的变量。谢谢Mauricio – user3313986

1

它用相应的POST字段的内容创建变量$ carModel,$ year等,或者如果没有任何内容,则返回null。

1
<?php 
// builds an array 
$expected = array('carModel', 'year', 'bodyStyle'); 
// loops over the array keys (carModel, year...) 
foreach($expected AS $key) { 
    // checks, if this key is found in the incomming POST array and not empty 
    if (!empty($_POST[ $key ])) { 
     // assigns the value of POST, to a variable under the key name 
     ${$key} = $_POST[ $key ]; 
    } else { 
     // or nulls it, which is totally pointless :) 
     ${$key} = NULL; 
    } 
} 
?> 

$ expected数组的意图是为POST数组键提供白名单。 有更好的实现方法,特别是filter_input(),filter_input_array()。

示例代码 http://www.php.net/manual/en/function.filter-input-array.php

+0

谢谢Jens-André。 filter-input-array看起来像是一个更好的解决方案。 – user3313986

0

如果后期数据为例

$_POST["carModel"] = "BMW"; 
$_POST["year"] = 2013; 

在它将手段......

$carModel = "BMW"; 
$year = 2013; 
$bodyStyle = null; 

是一样

extract($_POST);