-1

我当前的代码会冗长且重复,有什么方法可以让我遍历发布的变量并检查它们是否是使用 isset() 函数设置的。

这是我的代码:

$item_name = $_POST['item_name'];
$quantity = $_POST['qty'];
$model = $_POST['mdl'];
$weight = $_POST['wgt'];
$repornew = $_POST['ron'];
$date = $_POST['dob'];
$spec = $_POST['spc'];
$description = $_POST['desc'];
//retreive all values posted by user

if(isset($item_name) || isset($quantity) || isset($model) || isset($weight) || isset($repornew) || isset($date) || isset($spec) || isset($description)){

//send error back to user
}

使用数组或什至 JSON 来解决问题会是一个好主意吗?

我对我需要做什么有了大致的了解,但是将什么用作实现是困扰我的事情。

干杯

4

3 回答 3

1
foreach ($_POST as $key => $value) {
    // ...
}
于 2012-09-25T16:37:58.093 回答
1

要遍历 POST 变量并检查它们是否已提交:

$vars = array('item_name','qty','mdl','wgt','ron','dob','spc','desc');
$ok = 1;
foreach ($vars as $value) {
    if (!isset($_POST[$value]])) $ok = 0;
}

if (!$ok) echo 'Not everything is set!';
else echo 'Alright! Everything\'s right!';
于 2012-09-25T16:41:32.223 回答
1

您可以这样做的另一种方法:

$required_keys = array('keys','you','require');
$entered_keys = array_keys($_POST);

if (count(array_diff($required_keys,$entered_keys)) == 0) {
  // everything entered
} else {
  // something missing
}
于 2012-09-25T16:42:44.583 回答