php 如何将发布数据放入 CodeIgniter 中的数组中?帖子项目是数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20292828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:02:11  来源:igfitidea点击:

How can I get post data into an array in CodeIgniter? post items are arrays

phparrayscodeigniter

提问by TopTomato

In CodeIgniter, I'm trying to accomplish a batch update from form inputs that share the same name. But don't know how to get post data into an array. A simplified view of the form is as follows:

在 CodeIgniter 中,我试图从共享相同名称的表单输入中完成批量更新。但不知道如何将发布数据放入数组。表格的简化视图如下:

<input name="id[]" value="1"/><input name = title[] value="some-title"/><input name     ="sort_order[]" value="1"/>

<input name="id[]" value="2"/><input name = title[] value="some-tuttle"/><input name="sort_order[]" value="2"/>

<input name="id[]" value="3"/><input name = title[] value="some-turtle"/><input name="sort_order[]" value="3"/>

In my controller I have this for now:

在我的控制器中,我现在有这个:

function set_sort_order(){
    $data = array(
        array('id' => 1,'sort_order' => 14),
        array('id' => 2,'sort_order' => 5),
        array('id' => 3,'sort_order' => 9)
    );
    $this->db->update_batch('press_releases', $data, 'id');//works!
    $this->load->view(pr_listing);
}

The array is hard-wired to test in the input_batch function, which is working. So how can I get the post data into an array?

该数组是硬连线以在 input_batch 函数中进行测试,该函数正在工作。那么如何将帖子数据放入数组中呢?

回答by Naveed Hasan

$id = $this->input->post('id');
$sort_order = $this->input->post('sort_order');
$data = array();
foreach($id as $key=>$val)
{
  $data[] = array('id'=>$val,'sort_order'=>$sort_order[$key]);
}

回答by Mike Brant

Just by nature of the way the input fields are named using bracket notation (i.e. fieldname[]) will cause PHP to automatically populate data from these fields into an array. Simple access them like:

根据输入字段的命名方式,使用方括号表示法(即fieldname[])会导致 PHP 自动将这些字段中的数据填充到数组中。简单访问它们,如:

$ids = $_POST['id'];
$titles = $_POST['title'];
// etc.

You can easily combine these into a multidimensional array

您可以轻松地将这些组合成一个多维数组

$final_array = array();
$length = count($ids);
for($i = 0; $i < $length; $i++) {
    $final_array[$i]['id'] = $ids[$i];
    $final_array[$i]['title'] = $titles[$i];
    // etc.
}
var_dump($final_array);

Note: I did not show any input data validation/cleansing steps in my example. You probably want to verify input data exists, is in proper format, etc. before working with it.

注意:在我的示例中,我没有显示任何输入数据验证/清理步骤。在使用之前,您可能想要验证输入数据是否存在、格式是否正确等。