如何在CodeIgniter中获取和计算post变量(数组)?

时间:2014-06-24 11:00:21

标签: php arrays codeigniter post

我在视图中有表单(我正在使用codeigniter),在表单中有一个元素(数组),如下面的代码所示:

<table class="table table-stripped table-bordered" id="tbl-obat">
    <colgroup>
        <col class="con0">
        <col class="con1">
        <col class="con0">
        <col class="con1">
        <col class="con0">
    </colgroup>
    <thead>
        <tr>
            <th>No.</th>
            <th>Obat</th>
            <th>Dosis</th>
            <th>Satuan</th>
            <th>Jumlah</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                 <div id="1">1</div>
                 <input type="hidden" name="kd_obat_1" id="kd_obat_1" class="kd_obat" value="02">
            </td>
            <td>
                 <input type="text" name="nama_obat_1" id="nama_obat_1" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
            </td>
            <td>
                <input type="text" name="dosis_1" id="dosis_1" class="dosis input-small valid">
            </td>
            <td>
                <select name="satuan_1" id="satuan_1" class="satuan uniformselect valid" style="width:100px;">
                     <option name="-">Pilih Satuan</option>
                     <option value="KSKO-01">AMPUL</option>
                     <option value="KSKO-02">BUAH</option>
                     <option value="KSKO-03">BOTOL</option>
                     <option value="KSKO-04">BUNGKUS</option>
                     <option value="KSKO-05">KAPLET</option>
                </select>
            </td>
            <td>
                <input type="text" name="jumlah_1" id="jumlah_1" class="jumlah input-large valid">
            </td>
        </tr>
        <tr>
            <td>
                <div id="2">2</div>
                <input type="hidden" name="kd_obat_2" id="kd_obat_2" class="kd_obat" value="01">
            </td>
            <td>
                <input type="text" name="nama_obat_2" id="nama_obat_2" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
            </td>
            <td>
                <input type="text" name="dosis_2" id="dosis_2" class="dosis input-small valid">
            </td>
            <td>
                <select name="satuan_2" id="satuan_2" class="satuan uniformselect valid" style="width:100px;">
                <option name="-">Pilih Satuan</option>
                <option value="KSKO-01">AMPUL</option>
                <option value="KSKO-02">BUAH</option>
                <option value="KSKO-03">BOTOL</option>
                <option value="KSKO-04">BUNGKUS</option>
                <option value="KSKO-05">KAPLET</option>
            </select>
        </td>
        <td>
            <input type="text" name="jumlah_2" id="jumlah_2" class="jumlah input-large valid">
        </td>
    </tr>
</tbody>
</table>

如何计算数组并​​在控制器codeigniter中获取post值?我尝试这段代码不起作用:

foreach ($_POST as $key=>$val) {
    $$key = $val;
}

$obat = array();

$i = 1;
while(${"nama_obat_".$i}) {
    if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== "")
    {
         $obat[$i]['kd_trans_pelayanan'] = $trans_id;
         $obat[$i]['nama_obat'] = ${"nama_obat_".$i};
         $obat[$i]['dosis'] = ${"dosis_".$i};
         $obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
         $obat[$i]['qty'] = ${"jumlah_".$i};

        $i++;
    } else {
        exit(1);
    }
}

echo '<pre>';
print_r($obat);

提前致谢!

编辑:

我需要根据用户输入计算名称为'kd_obat_x'的字段x = 1 to n我需要算法来根据用户输入获取多少变量,等等获取数据。这是我的完整代码:

view.php

<h4>Step 3: Obat</h4>
<p>
    <table class="table table-stripped table-bordered" id="tbl-obat">
        <colgroup>
            <col class="con0" />
            <col class="con1" />
            <col class="con0" />
            <col class="con1" />
            <col class="con0" />
        </colgroup>
        <thead>
            <tr>
                <th>No.</th>
                <th>Obat</th>
                <th>Dosis</th>
                <th>Satuan</th>
                <th>Jumlah</th>
        </thead>
        <tbody></tbody>
    </table>
</p>
<p>
    <a href="#" id="addObat" class="btn btn-primary btn-rounded"><i class="icon-plus icon-white"></i>&nbsp;Tambah</a>
    <a href="#" id="removeObat" class="btn btn-danger btn-rounded"><i class="icon-trash icon-white"></i>&nbsp;Hapus</a>
</p>

my.js

<script type="text/javascript">
    // Autocomplete Obat
    jQuery(function() {
    var counter3 = 1;
    var options = {
        source: '<?php echo base_url(); ?>admin/autoCompleteObat',
        minLength: 2,
        focus: function( event, ui ) {
                    jQuery('#nama_obat_'+counter3).val(ui.item.value);
                    jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
        },
        select: function( event, ui ) {
                    //event.preventDefault();
                    jQuery('#nama_obat_'+counter3).val(ui.item.value);
                    jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);                      
        },
        messages: {
                noResults:  ''
        }
    };

    jQuery('input.nama_obat').live("keydown.autocomplete", function() {
        jQuery(this).autocomplete(options);
    });

    var addInput = function() {
        if (counter3 > 1){
            jQuery('a#removeObat').removeAttr('disabled');
        }

        var inputHTML = '<tr><td><div id="'+counter3+'">'+counter3+'</div><input type="hidden" name="kd_obat_'+counter3+'" id="kd_obat_'+counter3+'" class="kd_obat" /></td><td><input type="text" name="nama_obat_'+counter3+'" id="nama_obat_'+counter3+'" class="nama_obat input-large" /></td><td><input type="text" name="dosis_'+counter3+'" id="dosis_'+counter3+'" class="dosis input-small" /></td><td><select name="satuan_'+counter3+'" id="satuan_'+counter3+'" class="satuan uniformselect" style="width:100px;"><option name="-">Pilih Satuan</option><?php foreach($list_satuan_kecil as $lsk) : ?><option value="<?php echo $lsk['kd_sat_kecil_obat']; ?>"><?php echo $lsk['sat_kecil_obat']; ?></option><?php endforeach; ?></select></td><td><input type="text" name="jumlah_'+counter3+'" id="jumlah_'+counter3+'" class="jumlah input-large" /></td></tr>';

        jQuery(inputHTML).appendTo("table#tbl-obat tbody");
        jQuery("input.nama_obat:last").focus();
        jQuery('html, body').animate({
            scrollTop: jQuery("input.nama_obat:last").offset().top
        }, 2000);
        counter3++;
    };

    var removeInput = function() {
        counter3--;
        if(counter3 == 1){
            jQuery('a#removeObat').attr('disabled','disabled');
            //alert("Minimal sisa 1!");
            counter3++;
            //console.log('Jika Counter == 1 :' + counter3);
        }else{
            jQuery("table#tbl-obat tbody tr:last").remove();
            //console.log('Jika Counter != 1 :' + counter3);
        }
        jQuery("input.nama_obat:last").focus();
        jQuery('html, body').animate({
            scrollTop: jQuery("input.nama_obat:last").offset().top
        }, 2000);   
    };

    if (!jQuery("table#tbl-obat tbody").find("input.nama_obat").length) {
        addInput();
    }

    jQuery("a#addObat").click(addInput);
    jQuery("a#removeObat").click(removeInput);
}); 
</script>

admin.php(控制器)

function autoCompleteObat()
{
    if (isset($_REQUEST['term'])){
      $q = strtolower($_GET['term']);
      $output = $this->m_crud->get_obat($q);
      $this->output->set_content_type('application/json')->set_output(json_encode($output));
    }
}

/***MASTER PELAYANAN***/
function pelayanan($par1 = '', $par2 = '', $par3 = '')
{
    if (!$this->session->userdata('logged_in') == true)
    {
        redirect('login');
    }

    if ($par1 == 'tambah') {
        $trans_id                           = $this->m_crud->generate_transaksi();
        $pelayanan['kd_trans_pelayanan']    = $trans_id;
        $pelayanan['kd_rekam_medis']        = $this->input->post('kd_rekam_medis');
        $pelayanan['tgl_pelayanan']         = $this->functions->convert_date_sql($this->input->post('tgl_pelayanan'));
        $pelayanan['kd_jenis_layanan']      = $this->input->post('kd_jenis_layanan');
        $pelayanan['kd_unit_pelayanan']     = $this->input->post('kd_unit_pelayanan');
        $pelayanan['kd_puskesmas']          = 'P3271010101'; //$this->session->userdata('kd_puskesmas'); // harusnya diambil dari session
        $pelayanan['kd_dokter']             = $this->input->post('kd_dokter');
        $pelayanan['kd_petugas']            = $this->input->post('kd_petugas');
        $pelayanan['kd_status_pasien']      = $this->input->post('kd_status_pasien'); // blm
        $pelayanan['anamnesa']              = $this->input->post('anamnesa');
        $pelayanan['cat_fisik']             = $this->input->post('cat_fisik');
        $pelayanan['cat_dokter']            = $this->input->post('cat_dokter');
        $pelayanan['kd_bed']                = $this->input->post('kd_bed');
        $pelayanan['no_rujukan']            = $this->input->post('no_rujukan');
        $pelayanan['tempat_rujukan']        = $this->input->post('tempat_rujukan');

        // Pelayanan Obat
        $obat = array();

        $i = 1;
        while(${"nama_obat_".$i}) {
            if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== ""){
                $obat[$i]['kd_trans_pelayanan'] = $trans_id;
                $obat[$i]['nama_obat'] = ${"nama_obat_".$i};
                $obat[$i]['dosis'] = ${"dosis_".$i};
                $obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
                $obat[$i]['qty'] = ${"jumlah_".$i};

                   /* insert db here */                                        

                $i++;
            } else {
                exit(1);
            }

        }


        echo '<pre>';
        print_r($obat);
     }
}

最后我的模型 m_crud.php

function get_obat($q){
    $this->db->select('kd_obat,nama_obat');
    $this->db->like('nama_obat', $q);
    $this->db->or_like('kd_obat', $q);

    $query = $this->db->get('obat');
    $results = array();
    if($query->num_rows > 0){
        $i = 1;
        foreach ($query->result_array() as $row){
            $results[$i]['label'] = $row['kd_obat'].' - '.$row['nama_obat']; //build an array
            $results[$i]['value'] = htmlentities(stripslashes($row['nama_obat']));
            $results[$i]['kd_obat'] = htmlentities(stripslashes($row['kd_obat']));

            $i++;
        }
    }
    return $results;
}    

4 个答案:

答案 0 :(得分:1)

您可以将以下代码段用于帖子值:

$this->input->post(); 

Count Array元组:

$elements = count($this->input->post());

答案 1 :(得分:1)

你可以用&#39; kd_obat _&#39;来计算所有元素。使用此代码:

$count=0;
foreach($arr as $key=>$value){
$pos = strpos($key,'kd_obat_');
if($pos!==false){
    $count++;
}else{
     continue;  
}
}
echo $count;

答案 2 :(得分:0)

您可以使用输入库在codeIgniter Framework中获取“POST”数据,

请在您的代码中添加以下代码,您将获得帖子类型的数组。

 $postData = $this->input->post();  print_r($postData);exit; 

希望这对你有用。

答案 3 :(得分:0)

假设您想要nama_obat_1, nama_obat_2, nama_obat_3, etc

的值

首先,您需要在名称字段中指明一个数组,如下所示

nama_obat[] for the first field, nama_obat[] for the second field and so on

您可以选择这样做

nama_obat[1] for the first field, nama_obat[2] for the second field and so on

如果您var_dump() $this->input->post('nama_obat'),请在您的控制器中 将输出您的值数组。

然后,对于计数部分,您可以使用PHP count() function

如果您的$this->input->post('nama_obat');是一个单级数组,那么您可以使用

计数($这 - &GT;输入 - &GT;柱( 'nama_obat')); //或将其存储在变量中然后计算

如果您的数组是多级数组,如

array(
'foo' => 'bar',
'myfoo' => array('mybar'=> 'myfoo')
)

然后你可以使用

count($this->input->post('nama_obat'), COUNT_RECURSIVE); // or store it in a variable then count it