简体   繁体   中英

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

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:

<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?

$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]);
}

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

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM