使用foreach()和php表单以及自定义函数


Using foreach() and php form and custom fucntion

我有一个get函数,它可以返回已输入的项,效果很好。这在输入类中:

public static function get($item){
    if(isset($_POST[$item])){
        return $_POST[$item];
    } else if(isset($_GET[$item])){
        return $_GET[$item];
    }
    return '';
    }

现在我正试图在foreach循环中使用它,但遇到了一些问题——我想这是因为它没有返回数组吗?

以下是表单片段:

<tr>
    <td><input type="text" class="form-control" name="inventory_item_id[]"></td>
    <td><input type="text" class="form-control" name="inventory_record_amount[]"></td>
    <td><input type="text" class="form-control" name="inventory_record_orders[]"></td>
    <td><input type="text" class="form-control" name="inventory_record_sales[]"></td>
</tr>

现在,当我做以下事情时:

$invItems = Input::get('inventory_item_id');
foreach($invItems as $a => $b) {
    //some code here
}

博士风暴对我喊道:

为foreach()提供的参数无效。预期类型:数组或对象,实际类型:字符串。

有什么想法吗?

当您第一次在页面中输入时,可能会发生这种情况。这是因为在第一个请求中,您没有任何参数。请使用GET,并且您没有使用POST请求加载页面,因此您还没有任何数组。

为了避免此错误,您无法验证$invItems是否为数组。

$invItems = Input::get('inventory_item_id');
if (is_array($invItems)){
  foreach($invItems as $a => $b) {
     //some code here
  }
}