2014-03-28 53 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);