在php中循环遍历多个数组

时间:2014-01-16 06:16:09

标签: php mysql foreach

我想在“protocol”字段下的表“service_providers”中插入三个协议,在“plateform”字段下的同一个表中插入三个平台,当我点击提交按钮时,应在“service_providers”表中插入三个记录。

admin / protocol“method =”post“>                                                   协议                                                                                                                                                                                                                                             。平台                                                                                                                                                                                                                                           

这是行动代码

 <?php 

             $service_id  = $this->db->insert_id();

                      $protocols = $this->input->post('protocol');
                      $plateform     = $this->input->post('plateform');
                        foreach($protocols as $protocol){
                              foreach($protocols as $protocol){
                                    $data= array(
                                        'protocols' => $protocol,
                                        'country'   => $country
                                        );  

                                $this->db->insert('service_providers',$data);
                              }
                        }

当我编码那样的六个记录插入时,这是错误的

 <?php 

                  $protocols = $this->input->post('protocol');
                  $plateform     = $this->input->post('plateform');
                    foreach($protocols as $protocol){
                          foreach($plateforms as $plateform){
                                $data= array(
                                    'protocols' => $protocol,
                                    'plateform' => $plateform
                                    );  


                          }
                $this->db->insert('service_providers',$data);
                    }


?>

当我编码时,这三个记录插入,这是正确但内部foreach循环的值不插入如何解决这个我想在数据库中的那样

id       protocol      plateform     service_id 
1      PPTP      Windows      100
2     OpenVPN    Andriod      100
3     LPTP       iOS           100

1 个答案:

答案 0 :(得分:0)

在您的操作中尝试此代码: 这仅在协议和平台具有多个参数时才有效。

$protocols = $this->input->post('protocol');
$plateform     = $this->input->post('plateform');
$k =0;

foreach($protocols as $protocol){

        $data= array(
        'protocols' => $protocol,
        'plateform' => $plateform[$k]
        );  
        $this->db->insert('service_providers',$data);
        $k++;
}